aboutsummaryrefslogtreecommitdiffhomepage
path: root/src
diff options
context:
space:
mode:
authorGravatar Alistair Veitch <aveitch@google.com>2015-08-28 14:35:49 -0700
committerGravatar Alistair Veitch <aveitch@google.com>2015-08-28 14:35:49 -0700
commitbff9cf52ed6407862ce96ddfdcd8e97e56cdc520 (patch)
treeadcefb4d7740776b4e44a57336308c31dc0ef099 /src
parent6afe53f2360a20a4d3abda60cfdde576c29b9857 (diff)
parent808e5ae95f2fba44d2da925e8da0eaa5ce5c6585 (diff)
Merge branch 'master' into tracing_api
Diffstat (limited to 'src')
-rw-r--r--src/compiler/csharp_generator.cc62
-rw-r--r--src/compiler/csharp_generator.h2
-rw-r--r--src/core/census/grpc_filter.c2
-rw-r--r--src/core/census/grpc_filter.h6
-rw-r--r--src/core/channel/compress_filter.h2
-rw-r--r--src/core/channel/http_client_filter.c33
-rw-r--r--src/core/client_config/resolver_factory.c8
-rw-r--r--src/core/client_config/resolver_factory.h12
-rw-r--r--src/core/client_config/resolver_registry.c91
-rw-r--r--src/core/client_config/resolver_registry.h15
-rw-r--r--src/core/client_config/resolvers/dns_resolver.c25
-rw-r--r--src/core/client_config/resolvers/sockaddr_resolver.c49
-rw-r--r--src/core/client_config/resolvers/zookeeper_resolver.c11
-rw-r--r--src/core/profiling/basic_timers.c10
-rw-r--r--src/core/security/client_auth_filter.c3
-rw-r--r--src/core/security/credentials.c35
-rw-r--r--src/core/security/google_default_credentials.c6
-rw-r--r--src/core/support/log_win32.c10
-rw-r--r--src/core/support/time_posix.c14
-rw-r--r--src/core/support/time_precise.h (renamed from src/core/profiling/timers_preciseclock.h)56
-rw-r--r--src/core/support/time_win32.c4
-rw-r--r--src/core/surface/call.c5
-rw-r--r--src/core/surface/channel.c44
-rw-r--r--src/core/surface/init.c8
-rw-r--r--src/core/surface/secure_channel_create.c4
-rw-r--r--src/core/transport/chttp2/stream_lists.c44
-rw-r--r--src/core/transport/metadata.c24
-rw-r--r--src/core/transport/metadata.h1
-rw-r--r--src/cpp/client/create_channel.cc6
-rw-r--r--src/cpp/client/secure_credentials.cc21
-rw-r--r--src/cpp/common/auth_property_iterator.cc6
-rw-r--r--src/cpp/common/call.cc11
-rw-r--r--src/cpp/common/secure_auth_context.cc17
-rw-r--r--src/cpp/common/secure_auth_context.h6
-rw-r--r--src/cpp/server/secure_server_credentials.cc2
-rw-r--r--src/cpp/server/server.cc11
-rw-r--r--src/cpp/server/server_context.cc7
-rw-r--r--src/cpp/util/string_ref.cc8
-rw-r--r--src/csharp/.gitignore3
-rw-r--r--src/csharp/Grpc.Core.Tests/Grpc.Core.Tests.csproj1
-rw-r--r--src/csharp/Grpc.Core.Tests/MarshallingErrorsTest.cs176
-rw-r--r--src/csharp/Grpc.Core.Tests/MetadataTest.cs11
-rw-r--r--src/csharp/Grpc.Core.Tests/MockServiceHelper.cs80
-rw-r--r--src/csharp/Grpc.Core/Internal/AsyncCall.cs17
-rw-r--r--src/csharp/Grpc.Core/Internal/AsyncCallBase.cs50
-rw-r--r--src/csharp/Grpc.Core/Internal/AsyncCallServer.cs5
-rw-r--r--src/csharp/Grpc.Core/Marshaller.cs2
-rw-r--r--src/csharp/Grpc.Core/Metadata.cs8
-rw-r--r--src/csharp/Grpc.Core/VersionInfo.cs4
-rw-r--r--src/csharp/Grpc.Examples.MathClient/MathClient.cs2
-rw-r--r--src/csharp/Grpc.Examples.MathServer/MathServer.cs2
-rw-r--r--src/csharp/Grpc.Examples.Tests/Grpc.Examples.Tests.csproj7
-rw-r--r--src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs26
-rw-r--r--src/csharp/Grpc.Examples.Tests/packages.config2
-rw-r--r--src/csharp/Grpc.Examples/Grpc.Examples.csproj7
-rw-r--r--src/csharp/Grpc.Examples/Math.cs1651
-rw-r--r--src/csharp/Grpc.Examples/MathExamples.cs28
-rw-r--r--src/csharp/Grpc.Examples/MathGrpc.cs72
-rw-r--r--src/csharp/Grpc.Examples/MathServiceImpl.cs10
-rw-r--r--src/csharp/Grpc.Examples/packages.config2
-rw-r--r--src/csharp/Grpc.Examples/proto/math.proto16
-rw-r--r--src/csharp/Grpc.HealthCheck.Tests/Grpc.HealthCheck.Tests.csproj8
-rw-r--r--src/csharp/Grpc.HealthCheck.Tests/HealthClientServerTest.cs4
-rw-r--r--src/csharp/Grpc.HealthCheck.Tests/HealthServiceImplTest.cs2
-rw-r--r--src/csharp/Grpc.HealthCheck.Tests/packages.config2
-rw-r--r--src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.csproj8
-rw-r--r--src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.nuspec2
-rw-r--r--src/csharp/Grpc.HealthCheck/Health.cs716
-rw-r--r--src/csharp/Grpc.HealthCheck/HealthGrpc.cs10
-rw-r--r--src/csharp/Grpc.HealthCheck/HealthServiceImpl.cs6
-rw-r--r--src/csharp/Grpc.HealthCheck/packages.config2
-rw-r--r--src/csharp/Grpc.HealthCheck/proto/health.proto8
-rw-r--r--src/csharp/Grpc.IntegrationTesting/Empty.cs284
-rw-r--r--src/csharp/Grpc.IntegrationTesting/Grpc.IntegrationTesting.csproj16
-rw-r--r--src/csharp/Grpc.IntegrationTesting/InteropClient.cs151
-rw-r--r--src/csharp/Grpc.IntegrationTesting/InteropClientServerTest.cs2
-rw-r--r--src/csharp/Grpc.IntegrationTesting/InteropServer.cs3
-rw-r--r--src/csharp/Grpc.IntegrationTesting/Messages.cs3205
-rw-r--r--src/csharp/Grpc.IntegrationTesting/SslCredentialsTest.cs4
-rw-r--r--src/csharp/Grpc.IntegrationTesting/Test.cs48
-rw-r--r--src/csharp/Grpc.IntegrationTesting/TestCredentials.cs2
-rw-r--r--src/csharp/Grpc.IntegrationTesting/TestGrpc.cs110
-rw-r--r--src/csharp/Grpc.IntegrationTesting/TestServiceImpl.cs23
-rw-r--r--src/csharp/Grpc.IntegrationTesting/packages.config1
-rw-r--r--src/csharp/Grpc.IntegrationTesting/proto/empty.proto2
-rw-r--r--src/csharp/Grpc.IntegrationTesting/proto/messages.proto36
-rw-r--r--src/csharp/Grpc.IntegrationTesting/proto/test.proto2
-rw-r--r--src/csharp/Grpc.Tools.nuspec7
-rw-r--r--src/csharp/README.md6
-rw-r--r--src/csharp/build_packages.bat9
-rw-r--r--src/csharp/ext/grpc_csharp_ext.c8
-rwxr-xr-xsrc/csharp/generate_proto_csharp.sh8
-rw-r--r--src/node/ext/call.cc23
-rw-r--r--src/node/ext/channel.cc2
-rw-r--r--src/node/ext/credentials.cc11
-rw-r--r--src/node/ext/server.cc51
-rw-r--r--src/node/ext/server.h3
-rw-r--r--src/node/ext/server_credentials.cc7
-rw-r--r--src/node/index.js15
-rw-r--r--src/node/interop/interop_client.js8
-rw-r--r--src/node/src/client.js61
-rw-r--r--src/node/src/metadata.js181
-rw-r--r--src/node/src/server.js86
-rw-r--r--src/node/test/call_test.js2
-rw-r--r--src/node/test/end_to_end_test.js2
-rw-r--r--src/node/test/health_test.js2
-rw-r--r--src/node/test/interop_sanity_test.js2
-rw-r--r--src/node/test/math_client_test.js2
-rw-r--r--src/node/test/metadata_test.js193
-rw-r--r--src/node/test/server_test.js31
-rw-r--r--src/node/test/surface_test.js78
-rw-r--r--src/objective-c/GRPCClient/private/GRPCSecureChannel.m7
-rw-r--r--src/objective-c/README.md2
-rw-r--r--src/objective-c/tests/LocalClearTextTests.m2
-rw-r--r--src/php/ext/grpc/channel.c2
-rw-r--r--src/php/ext/grpc/credentials.c6
-rw-r--r--src/php/ext/grpc/server_credentials.c2
-rw-r--r--src/php/tests/generated_code/AbstractGeneratedCodeTest.php4
-rwxr-xr-xsrc/php/tests/interop/interop_client.php11
-rw-r--r--src/python/README.md14
-rw-r--r--src/python/grpcio/grpc/_adapter/_c/types/channel.c5
-rw-r--r--src/python/grpcio/grpc/_adapter/_c/types/client_credentials.c20
-rw-r--r--src/python/grpcio/grpc/_adapter/_c/types/server_credentials.c13
-rw-r--r--src/python/grpcio/grpc/_adapter/_intermediary_low.py5
-rw-r--r--src/python/grpcio/grpc/_adapter/fore.py2
-rw-r--r--src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxd2
-rw-r--r--src/python/grpcio/grpc/_links/service.py22
-rw-r--r--src/python/grpcio/grpc/beta/__init__.py28
-rw-r--r--src/python/grpcio/grpc/beta/_connectivity_channel.py148
-rw-r--r--src/python/grpcio/grpc/beta/beta.py114
-rw-r--r--src/python/grpcio/grpc/beta/utilities.py161
-rw-r--r--src/python/grpcio/grpc/framework/core/_context.py2
-rw-r--r--src/python/grpcio/grpc/framework/core/_emission.py3
-rw-r--r--src/python/grpcio/grpc/framework/core/_end.py6
-rw-r--r--src/python/grpcio/grpc/framework/core/_expiration.py2
-rw-r--r--src/python/grpcio/grpc/framework/core/_ingestion.py66
-rw-r--r--src/python/grpcio/grpc/framework/core/_interfaces.py8
-rw-r--r--src/python/grpcio/grpc/framework/core/_operation.py2
-rw-r--r--src/python/grpcio/grpc/framework/core/_reception.py2
-rw-r--r--src/python/grpcio/grpc/framework/core/_transmission.py14
-rw-r--r--src/python/grpcio/grpc/framework/crust/__init__.py30
-rw-r--r--src/python/grpcio/grpc/framework/crust/_calls.py204
-rw-r--r--src/python/grpcio/grpc/framework/crust/_control.py545
-rw-r--r--src/python/grpcio/grpc/framework/crust/_service.py166
-rw-r--r--src/python/grpcio/grpc/framework/crust/implementations.py352
-rw-r--r--src/python/grpcio/grpc/framework/interfaces/base/base.py21
-rw-r--r--src/python/grpcio_test/grpc_interop/client.py8
-rw-r--r--src/python/grpcio_test/grpc_interop/methods.py16
-rw-r--r--src/python/grpcio_test/grpc_test/_adapter/_links_test.py4
-rw-r--r--src/python/grpcio_test/grpc_test/_core_over_links_base_interface_test.py24
-rw-r--r--src/python/grpcio_test/grpc_test/_crust_over_core_over_links_face_interface_test.py159
-rw-r--r--src/python/grpcio_test/grpc_test/_cython/adapter_low_test.py2
-rw-r--r--src/python/grpcio_test/grpc_test/_links/_transmission_test.py24
-rw-r--r--src/python/grpcio_test/grpc_test/beta/__init__.py30
-rw-r--r--src/python/grpcio_test/grpc_test/beta/_connectivity_channel_test.py180
-rw-r--r--src/python/grpcio_test/grpc_test/beta/_utilities_test.py123
-rw-r--r--src/python/grpcio_test/grpc_test/framework/_crust_over_core_face_interface_test.py111
-rw-r--r--src/python/grpcio_test/grpc_test/framework/interfaces/base/test_cases.py2
-rw-r--r--src/python/grpcio_test/grpc_test/framework/interfaces/face/_3069_test_constant.py37
-rw-r--r--src/python/grpcio_test/grpc_test/framework/interfaces/face/_blocking_invocation_inline_service.py9
-rw-r--r--src/python/grpcio_test/grpc_test/framework/interfaces/face/_event_invocation_synchronous_event_service.py11
-rw-r--r--src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py17
-rw-r--r--src/python/grpcio_test/grpc_test/framework/interfaces/face/_stock_service.py2
-rw-r--r--src/python/grpcio_test/grpc_test/test_common.py5
-rw-r--r--src/ruby/ext/grpc/rb_channel.c2
-rw-r--r--src/ruby/ext/grpc/rb_credentials.c11
-rw-r--r--src/ruby/ext/grpc/rb_server_credentials.c5
167 files changed, 5632 insertions, 5461 deletions
diff --git a/src/compiler/csharp_generator.cc b/src/compiler/csharp_generator.cc
index 9432bdda96..7b497df7f4 100644
--- a/src/compiler/csharp_generator.cc
+++ b/src/compiler/csharp_generator.cc
@@ -33,12 +33,18 @@
#include <cctype>
#include <map>
+#include <sstream>
#include <vector>
+#include "src/compiler/csharp_generator.h"
#include "src/compiler/config.h"
#include "src/compiler/csharp_generator_helpers.h"
#include "src/compiler/csharp_generator.h"
+
+using google::protobuf::compiler::csharp::GetFileNamespace;
+using google::protobuf::compiler::csharp::GetClassName;
+using google::protobuf::compiler::csharp::GetUmbrellaClassName;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::Descriptor;
using grpc::protobuf::ServiceDescriptor;
@@ -55,47 +61,10 @@ using grpc_generator::StringReplace;
using std::map;
using std::vector;
+
namespace grpc_csharp_generator {
namespace {
-// TODO(jtattermusch): make GetFileNamespace part of libprotoc public API.
-// NOTE: Implementation needs to match exactly to GetFileNamespace
-// defined in csharp_helpers.h in protoc csharp plugin.
-// We cannot reference it directly because google3 protobufs
-// don't have a csharp protoc plugin.
-std::string GetFileNamespace(const FileDescriptor* file) {
- if (file->options().has_csharp_namespace()) {
- return file->options().csharp_namespace();
- }
- return file->package();
-}
-
-std::string ToCSharpName(const std::string& name, const FileDescriptor* file) {
- std::string result = GetFileNamespace(file);
- if (result != "") {
- result += '.';
- }
- std::string classname;
- if (file->package().empty()) {
- classname = name;
- } else {
- // Strip the proto package from full_name since we've replaced it with
- // the C# namespace.
- classname = name.substr(file->package().size() + 1);
- }
- result += StringReplace(classname, ".", ".Types.", false);
- return "global::" + result;
-}
-
-// TODO(jtattermusch): make GetClassName part of libprotoc public API.
-// NOTE: Implementation needs to match exactly to GetClassName
-// defined in csharp_helpers.h in protoc csharp plugin.
-// We cannot reference it directly because google3 protobufs
-// don't have a csharp protoc plugin.
-std::string GetClassName(const Descriptor* message) {
- return ToCSharpName(message->full_name(), message->file());
-}
-
std::string GetServiceClassName(const ServiceDescriptor* service) {
return service->name();
}
@@ -229,7 +198,7 @@ void GenerateMarshallerFields(Printer* out, const ServiceDescriptor *service) {
for (size_t i = 0; i < used_messages.size(); i++) {
const Descriptor *message = used_messages[i];
out->Print(
- "static readonly Marshaller<$type$> $fieldname$ = Marshallers.Create((arg) => arg.ToByteArray(), $type$.ParseFrom);\n",
+ "static readonly Marshaller<$type$> $fieldname$ = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), $type$.Parser.ParseFrom);\n",
"fieldname", GetMarshallerFieldName(message), "type",
GetClassName(message));
}
@@ -258,6 +227,19 @@ void GenerateStaticMethodField(Printer* out, const MethodDescriptor *method) {
out->Outdent();
}
+void GenerateServiceDescriptorProperty(Printer* out, const ServiceDescriptor *service) {
+ std::ostringstream index;
+ index << service->index();
+ out->Print("// service descriptor\n");
+ out->Print("public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor\n");
+ out->Print("{\n");
+ out->Print(" get { return $umbrella$.Descriptor.Services[$index$]; }\n",
+ "umbrella", GetUmbrellaClassName(service->file()), "index",
+ index.str());
+ out->Print("}\n");
+ out->Print("\n");
+}
+
void GenerateClientInterface(Printer* out, const ServiceDescriptor *service) {
out->Print("// client interface\n");
out->Print("public interface $name$\n", "name",
@@ -504,6 +486,7 @@ void GenerateService(Printer* out, const ServiceDescriptor *service) {
for (int i = 0; i < service->method_count(); i++) {
GenerateStaticMethodField(out, service->method(i));
}
+ GenerateServiceDescriptorProperty(out, service);
GenerateClientInterface(out, service);
GenerateServerInterface(out, service);
GenerateClientStub(out, service);
@@ -539,7 +522,6 @@ grpc::string GetServices(const FileDescriptor *file) {
out.Print("using System.Threading;\n");
out.Print("using System.Threading.Tasks;\n");
out.Print("using Grpc.Core;\n");
- // TODO(jtattermusch): add using for protobuf message classes
out.Print("\n");
out.Print("namespace $namespace$ {\n", "namespace", GetFileNamespace(file));
diff --git a/src/compiler/csharp_generator.h b/src/compiler/csharp_generator.h
index ec537d3f1d..90eb7e2984 100644
--- a/src/compiler/csharp_generator.h
+++ b/src/compiler/csharp_generator.h
@@ -36,6 +36,8 @@
#include "src/compiler/config.h"
+#include <google/protobuf/compiler/csharp/csharp_names.h>
+
namespace grpc_csharp_generator {
grpc::string GetServices(const grpc::protobuf::FileDescriptor *file);
diff --git a/src/core/census/grpc_filter.c b/src/core/census/grpc_filter.c
index fbedb35661..b78445595c 100644
--- a/src/core/census/grpc_filter.c
+++ b/src/core/census/grpc_filter.c
@@ -36,12 +36,12 @@
#include <stdio.h>
#include <string.h>
-#include "include/grpc/census.h"
#include "src/core/census/rpc_stat_id.h"
#include "src/core/channel/channel_stack.h"
#include "src/core/channel/noop_filter.h"
#include "src/core/statistics/census_interface.h"
#include "src/core/statistics/census_rpc_stats.h"
+#include <grpc/census.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/slice.h>
diff --git a/src/core/census/grpc_filter.h b/src/core/census/grpc_filter.h
index 1453c05d28..b3de3adc94 100644
--- a/src/core/census/grpc_filter.h
+++ b/src/core/census/grpc_filter.h
@@ -31,8 +31,8 @@
*
*/
-#ifndef GRPC_INTERNAL_CORE_CHANNEL_CENSUS_FILTER_H
-#define GRPC_INTERNAL_CORE_CHANNEL_CENSUS_FILTER_H
+#ifndef GRPC_INTERNAL_CORE_CENSUS_GRPC_FILTER_H
+#define GRPC_INTERNAL_CORE_CENSUS_GRPC_FILTER_H
#include "src/core/channel/channel_stack.h"
@@ -41,4 +41,4 @@
extern const grpc_channel_filter grpc_client_census_filter;
extern const grpc_channel_filter grpc_server_census_filter;
-#endif /* GRPC_INTERNAL_CORE_CHANNEL_CENSUS_FILTER_H */
+#endif /* GRPC_INTERNAL_CORE_CENSUS_GRPC_FILTER_H */
diff --git a/src/core/channel/compress_filter.h b/src/core/channel/compress_filter.h
index 0917e81ca4..415459bca6 100644
--- a/src/core/channel/compress_filter.h
+++ b/src/core/channel/compress_filter.h
@@ -36,7 +36,7 @@
#include "src/core/channel/channel_stack.h"
-#define GRPC_COMPRESS_REQUEST_ALGORITHM_KEY "internal:grpc-encoding-request"
+#define GRPC_COMPRESS_REQUEST_ALGORITHM_KEY "grpc-internal-encoding-request"
/** Compression filter for outgoing data.
*
diff --git a/src/core/channel/http_client_filter.c b/src/core/channel/http_client_filter.c
index 48c623d359..2b61d33c29 100644
--- a/src/core/channel/http_client_filter.c
+++ b/src/core/channel/http_client_filter.c
@@ -45,7 +45,6 @@ typedef struct call_data {
grpc_linked_mdelem content_type;
grpc_linked_mdelem user_agent;
int sent_initial_metadata;
- int sent_authority;
int got_initial_metadata;
grpc_stream_op_buffer *recv_ops;
@@ -64,7 +63,6 @@ typedef struct channel_data {
grpc_mdelem *scheme;
grpc_mdelem *content_type;
grpc_mdelem *status;
- grpc_mdelem *default_authority;
/** complete user agent mdelem */
grpc_mdelem *user_agent;
} channel_data;
@@ -103,7 +101,6 @@ static void hc_on_recv(void *user_data, int success) {
static grpc_mdelem *client_strip_filter(void *user_data, grpc_mdelem *md) {
grpc_call_element *elem = user_data;
- call_data *calld = elem->call_data;
channel_data *channeld = elem->channel_data;
/* eat the things we'd like to set ourselves */
if (md->key == channeld->method->key) return NULL;
@@ -111,10 +108,6 @@ static grpc_mdelem *client_strip_filter(void *user_data, grpc_mdelem *md) {
if (md->key == channeld->te_trailers->key) return NULL;
if (md->key == channeld->content_type->key) return NULL;
if (md->key == channeld->user_agent->key) return NULL;
- if (channeld->default_authority &&
- channeld->default_authority->key == md->key) {
- calld->sent_authority = 1;
- }
return md;
}
@@ -138,11 +131,6 @@ static void hc_mutate_op(grpc_call_element *elem,
GRPC_MDELEM_REF(channeld->method));
grpc_metadata_batch_add_head(&op->data.metadata, &calld->scheme,
GRPC_MDELEM_REF(channeld->scheme));
- if (channeld->default_authority && !calld->sent_authority) {
- grpc_metadata_batch_add_head(
- &op->data.metadata, &calld->authority,
- GRPC_MDELEM_REF(channeld->default_authority));
- }
grpc_metadata_batch_add_tail(&op->data.metadata, &calld->te_trailers,
GRPC_MDELEM_REF(channeld->te_trailers));
grpc_metadata_batch_add_tail(&op->data.metadata, &calld->content_type,
@@ -175,7 +163,6 @@ static void init_call_elem(grpc_call_element *elem,
call_data *calld = elem->call_data;
calld->sent_initial_metadata = 0;
calld->got_initial_metadata = 0;
- calld->sent_authority = 0;
calld->on_done_recv = NULL;
grpc_iomgr_closure_init(&calld->hc_on_recv, hc_on_recv, elem);
if (initial_op) hc_mutate_op(elem, initial_op);
@@ -257,8 +244,6 @@ static grpc_mdstr *user_agent_from_args(grpc_mdctx *mdctx,
static void init_channel_elem(grpc_channel_element *elem, grpc_channel *master,
const grpc_channel_args *channel_args,
grpc_mdctx *mdctx, int is_first, int is_last) {
- size_t i;
-
/* grab pointers to our data from the channel element */
channel_data *channeld = elem->channel_data;
@@ -267,21 +252,6 @@ static void init_channel_elem(grpc_channel_element *elem, grpc_channel *master,
path */
GPR_ASSERT(!is_last);
- channeld->default_authority = NULL;
- if (channel_args) {
- for (i = 0; i < channel_args->num_args; i++) {
- if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_DEFAULT_AUTHORITY)) {
- if (channel_args->args[i].type != GRPC_ARG_STRING) {
- gpr_log(GPR_ERROR, "%s: must be an string",
- GRPC_ARG_DEFAULT_AUTHORITY);
- } else {
- channeld->default_authority = grpc_mdelem_from_strings(
- mdctx, ":authority", channel_args->args[i].value.string);
- }
- }
- }
- }
-
/* initialize members */
channeld->te_trailers = grpc_mdelem_from_strings(mdctx, "te", "trailers");
channeld->method = grpc_mdelem_from_strings(mdctx, ":method", "POST");
@@ -306,9 +276,6 @@ static void destroy_channel_elem(grpc_channel_element *elem) {
GRPC_MDELEM_UNREF(channeld->content_type);
GRPC_MDELEM_UNREF(channeld->status);
GRPC_MDELEM_UNREF(channeld->user_agent);
- if (channeld->default_authority) {
- GRPC_MDELEM_UNREF(channeld->default_authority);
- }
}
const grpc_channel_filter grpc_http_client_filter = {
diff --git a/src/core/client_config/resolver_factory.c b/src/core/client_config/resolver_factory.c
index 6721977e21..5b859a8d10 100644
--- a/src/core/client_config/resolver_factory.c
+++ b/src/core/client_config/resolver_factory.c
@@ -45,6 +45,12 @@ void grpc_resolver_factory_unref(grpc_resolver_factory *factory) {
grpc_resolver *grpc_resolver_factory_create_resolver(
grpc_resolver_factory *factory, grpc_uri *uri,
grpc_subchannel_factory *subchannel_factory) {
- if (!factory) return NULL;
+ if (factory == NULL) return NULL;
return factory->vtable->create_resolver(factory, uri, subchannel_factory);
}
+
+char *grpc_resolver_factory_get_default_authority(
+ grpc_resolver_factory *factory, grpc_uri *uri) {
+ if (factory == NULL) return NULL;
+ return factory->vtable->get_default_authority(factory, uri);
+}
diff --git a/src/core/client_config/resolver_factory.h b/src/core/client_config/resolver_factory.h
index c5d85499c6..e243b23988 100644
--- a/src/core/client_config/resolver_factory.h
+++ b/src/core/client_config/resolver_factory.h
@@ -51,9 +51,16 @@ struct grpc_resolver_factory_vtable {
void (*ref)(grpc_resolver_factory *factory);
void (*unref)(grpc_resolver_factory *factory);
+ /** Implementation of grpc_resolver_factory_create_resolver */
grpc_resolver *(*create_resolver)(
grpc_resolver_factory *factory, grpc_uri *uri,
grpc_subchannel_factory *subchannel_factory);
+
+ /** Implementation of grpc_resolver_factory_get_default_authority */
+ char *(*get_default_authority)(grpc_resolver_factory *factory, grpc_uri *uri);
+
+ /** URI scheme that this factory implements */
+ const char *scheme;
};
void grpc_resolver_factory_ref(grpc_resolver_factory *resolver);
@@ -64,4 +71,9 @@ grpc_resolver *grpc_resolver_factory_create_resolver(
grpc_resolver_factory *factory, grpc_uri *uri,
grpc_subchannel_factory *subchannel_factory);
+/** Return a (freshly allocated with gpr_malloc) string representing
+ the default authority to use for this scheme. */
+char *grpc_resolver_factory_get_default_authority(
+ grpc_resolver_factory *factory, grpc_uri *uri);
+
#endif /* GRPC_INTERNAL_CORE_CONFIG_RESOLVER_FACTORY_H */
diff --git a/src/core/client_config/resolver_registry.c b/src/core/client_config/resolver_registry.c
index 16be2da994..37979b3b86 100644
--- a/src/core/client_config/resolver_registry.c
+++ b/src/core/client_config/resolver_registry.c
@@ -41,41 +41,33 @@
#define MAX_RESOLVERS 10
-typedef struct {
- char *scheme;
- grpc_resolver_factory *factory;
-} registered_resolver;
-
-static registered_resolver g_all_of_the_resolvers[MAX_RESOLVERS];
+static grpc_resolver_factory *g_all_of_the_resolvers[MAX_RESOLVERS];
static int g_number_of_resolvers = 0;
-static char *g_default_resolver_scheme;
+static char *g_default_resolver_prefix;
-void grpc_resolver_registry_init(const char *default_resolver_scheme) {
+void grpc_resolver_registry_init(const char *default_resolver_prefix) {
g_number_of_resolvers = 0;
- g_default_resolver_scheme = gpr_strdup(default_resolver_scheme);
+ g_default_resolver_prefix = gpr_strdup(default_resolver_prefix);
}
void grpc_resolver_registry_shutdown(void) {
int i;
for (i = 0; i < g_number_of_resolvers; i++) {
- gpr_free(g_all_of_the_resolvers[i].scheme);
- grpc_resolver_factory_unref(g_all_of_the_resolvers[i].factory);
+ grpc_resolver_factory_unref(g_all_of_the_resolvers[i]);
}
- gpr_free(g_default_resolver_scheme);
+ gpr_free(g_default_resolver_prefix);
}
-void grpc_register_resolver_type(const char *scheme,
- grpc_resolver_factory *factory) {
+void grpc_register_resolver_type(grpc_resolver_factory *factory) {
int i;
for (i = 0; i < g_number_of_resolvers; i++) {
- GPR_ASSERT(0 != strcmp(scheme, g_all_of_the_resolvers[i].scheme));
+ GPR_ASSERT(0 != strcmp(factory->vtable->scheme,
+ g_all_of_the_resolvers[i]->vtable->scheme));
}
GPR_ASSERT(g_number_of_resolvers != MAX_RESOLVERS);
- g_all_of_the_resolvers[g_number_of_resolvers].scheme = gpr_strdup(scheme);
grpc_resolver_factory_ref(factory);
- g_all_of_the_resolvers[g_number_of_resolvers].factory = factory;
- g_number_of_resolvers++;
+ g_all_of_the_resolvers[g_number_of_resolvers++] = factory;
}
static grpc_resolver_factory *lookup_factory(grpc_uri *uri) {
@@ -85,40 +77,57 @@ static grpc_resolver_factory *lookup_factory(grpc_uri *uri) {
if (!uri) return NULL;
for (i = 0; i < g_number_of_resolvers; i++) {
- if (0 == strcmp(uri->scheme, g_all_of_the_resolvers[i].scheme)) {
- return g_all_of_the_resolvers[i].factory;
+ if (0 == strcmp(uri->scheme, g_all_of_the_resolvers[i]->vtable->scheme)) {
+ return g_all_of_the_resolvers[i];
}
}
return NULL;
}
-grpc_resolver *grpc_resolver_create(
- const char *name, grpc_subchannel_factory *subchannel_factory) {
- grpc_uri *uri;
+static grpc_resolver_factory *resolve_factory(const char *target,
+ grpc_uri **uri) {
char *tmp;
grpc_resolver_factory *factory = NULL;
- grpc_resolver *resolver;
-
- uri = grpc_uri_parse(name, 1);
- factory = lookup_factory(uri);
- if (factory == NULL && g_default_resolver_scheme != NULL) {
- grpc_uri_destroy(uri);
- gpr_asprintf(&tmp, "%s%s", g_default_resolver_scheme, name);
- uri = grpc_uri_parse(tmp, 1);
- factory = lookup_factory(uri);
- if (factory == NULL) {
- grpc_uri_destroy(grpc_uri_parse(name, 0));
- grpc_uri_destroy(grpc_uri_parse(tmp, 0));
- gpr_log(GPR_ERROR, "don't know how to resolve '%s' or '%s'", name, tmp);
+
+ GPR_ASSERT(uri != NULL);
+ *uri = grpc_uri_parse(target, 1);
+ factory = lookup_factory(*uri);
+ if (factory == NULL) {
+ if (g_default_resolver_prefix != NULL) {
+ grpc_uri_destroy(*uri);
+ gpr_asprintf(&tmp, "%s%s", g_default_resolver_prefix, target);
+ *uri = grpc_uri_parse(tmp, 1);
+ factory = lookup_factory(*uri);
+ if (factory == NULL) {
+ grpc_uri_destroy(grpc_uri_parse(target, 0));
+ grpc_uri_destroy(grpc_uri_parse(tmp, 0));
+ gpr_log(GPR_ERROR, "don't know how to resolve '%s' or '%s'", target,
+ tmp);
+ }
+ gpr_free(tmp);
+ } else {
+ grpc_uri_destroy(grpc_uri_parse(target, 0));
+ gpr_log(GPR_ERROR, "don't know how to resolve '%s'", target);
}
- gpr_free(tmp);
- } else if (factory == NULL) {
- grpc_uri_destroy(grpc_uri_parse(name, 0));
- gpr_log(GPR_ERROR, "don't know how to resolve '%s'", name);
}
- resolver =
+ return factory;
+}
+
+grpc_resolver *grpc_resolver_create(
+ const char *target, grpc_subchannel_factory *subchannel_factory) {
+ grpc_uri *uri = NULL;
+ grpc_resolver_factory *factory = resolve_factory(target, &uri);
+ grpc_resolver *resolver =
grpc_resolver_factory_create_resolver(factory, uri, subchannel_factory);
grpc_uri_destroy(uri);
return resolver;
}
+
+char *grpc_get_default_authority(const char *target) {
+ grpc_uri *uri = NULL;
+ grpc_resolver_factory *factory = resolve_factory(target, &uri);
+ char *authority = grpc_resolver_factory_get_default_authority(factory, uri);
+ grpc_uri_destroy(uri);
+ return authority;
+}
diff --git a/src/core/client_config/resolver_registry.h b/src/core/client_config/resolver_registry.h
index 31aa47620a..5a7193b7ae 100644
--- a/src/core/client_config/resolver_registry.h
+++ b/src/core/client_config/resolver_registry.h
@@ -44,19 +44,22 @@ void grpc_resolver_registry_shutdown(void);
If \a priority is greater than zero, then the resolver will be eligible
to resolve names that are passed in with no scheme. Higher priority
resolvers will be tried before lower priority schemes. */
-void grpc_register_resolver_type(const char *scheme,
- grpc_resolver_factory *factory);
+void grpc_register_resolver_type(grpc_resolver_factory *factory);
-/** Create a resolver given \a name.
- First tries to parse \a name as a URI. If this succeeds, tries
+/** Create a resolver given \a target.
+ First tries to parse \a target as a URI. If this succeeds, tries
to locate a registered resolver factory based on the URI scheme.
If parsing or location fails, prefixes default_prefix from
- grpc_resolver_registry_init to name, and tries again (if default_prefix
+ grpc_resolver_registry_init to target, and tries again (if default_prefix
was not NULL).
If a resolver factory was found, use it to instantiate a resolver and
return it.
If a resolver factory was not found, return NULL. */
grpc_resolver *grpc_resolver_create(
- const char *name, grpc_subchannel_factory *subchannel_factory);
+ const char *target, grpc_subchannel_factory *subchannel_factory);
+
+/** Given a target, return a (freshly allocated with gpr_malloc) string
+ representing the default authority to pass from a client. */
+char *grpc_get_default_authority(const char *target);
#endif /* GRPC_INTERNAL_CORE_CLIENT_CONFIG_RESOLVER_REGISTRY_H */
diff --git a/src/core/client_config/resolvers/dns_resolver.c b/src/core/client_config/resolvers/dns_resolver.c
index 7b35b7902f..84643c464a 100644
--- a/src/core/client_config/resolvers/dns_resolver.c
+++ b/src/core/client_config/resolvers/dns_resolver.c
@@ -203,9 +203,6 @@ static grpc_resolver *dns_create(
grpc_subchannel_factory *subchannel_factory) {
dns_resolver *r;
const char *path = uri->path;
- grpc_arg default_host_arg;
- char *host;
- char *port;
if (0 != strcmp(uri->authority, "")) {
gpr_log(GPR_ERROR, "authority based uri's not supported");
@@ -214,17 +211,6 @@ static grpc_resolver *dns_create(
if (path[0] == '/') ++path;
- gpr_split_host_port(path, &host, &port);
-
- default_host_arg.type = GRPC_ARG_STRING;
- default_host_arg.key = GRPC_ARG_DEFAULT_AUTHORITY;
- default_host_arg.value.string = host;
- subchannel_factory = grpc_subchannel_factory_add_channel_arg(
- subchannel_factory, &default_host_arg);
-
- gpr_free(host);
- gpr_free(port);
-
r = gpr_malloc(sizeof(dns_resolver));
memset(r, 0, sizeof(*r));
gpr_ref_init(&r->refs, 1);
@@ -233,6 +219,7 @@ static grpc_resolver *dns_create(
r->name = gpr_strdup(path);
r->default_port = gpr_strdup(default_port);
r->subchannel_factory = subchannel_factory;
+ grpc_subchannel_factory_ref(subchannel_factory);
r->lb_policy_factory = lb_policy_factory;
return &r->base;
}
@@ -252,8 +239,16 @@ static grpc_resolver *dns_factory_create_resolver(
subchannel_factory);
}
+char *dns_factory_get_default_host_name(grpc_resolver_factory *factory,
+ grpc_uri *uri) {
+ const char *path = uri->path;
+ if (path[0] == '/') ++path;
+ return gpr_strdup(path);
+}
+
static const grpc_resolver_factory_vtable dns_factory_vtable = {
- dns_factory_ref, dns_factory_unref, dns_factory_create_resolver};
+ dns_factory_ref, dns_factory_unref, dns_factory_create_resolver,
+ dns_factory_get_default_host_name, "dns"};
static grpc_resolver_factory dns_resolver_factory = {&dns_factory_vtable};
grpc_resolver_factory *grpc_dns_resolver_factory_create() {
diff --git a/src/core/client_config/resolvers/sockaddr_resolver.c b/src/core/client_config/resolvers/sockaddr_resolver.c
index 8419873908..0d8540a566 100644
--- a/src/core/client_config/resolvers/sockaddr_resolver.c
+++ b/src/core/client_config/resolvers/sockaddr_resolver.c
@@ -166,8 +166,29 @@ static int parse_unix(grpc_uri *uri, struct sockaddr_storage *addr, int *len) {
return 1;
}
+
+static char *unix_get_default_authority(grpc_resolver_factory *factory,
+ grpc_uri *uri) {
+ return gpr_strdup("localhost");
+}
#endif
+static char *ip_get_default_authority(grpc_uri *uri) {
+ const char *path = uri->path;
+ if (path[0] == '/') ++path;
+ return gpr_strdup(path);
+}
+
+static char *ipv4_get_default_authority(grpc_resolver_factory *factory,
+ grpc_uri *uri) {
+ return ip_get_default_authority(uri);
+}
+
+static char *ipv6_get_default_authority(grpc_resolver_factory *factory,
+ grpc_uri *uri) {
+ return ip_get_default_authority(uri);
+}
+
static int parse_ipv4(grpc_uri *uri, struct sockaddr_storage *addr, int *len) {
const char *host_port = uri->path;
char *host;
@@ -313,20 +334,20 @@ static void sockaddr_factory_ref(grpc_resolver_factory *factory) {}
static void sockaddr_factory_unref(grpc_resolver_factory *factory) {}
-#define DECL_FACTORY(name) \
- static grpc_resolver *name##_factory_create_resolver( \
- grpc_resolver_factory *factory, grpc_uri *uri, \
- grpc_subchannel_factory *subchannel_factory) { \
- return sockaddr_create(uri, grpc_create_pick_first_lb_policy, \
- subchannel_factory, parse_##name); \
- } \
- static const grpc_resolver_factory_vtable name##_factory_vtable = { \
- sockaddr_factory_ref, sockaddr_factory_unref, \
- name##_factory_create_resolver}; \
- static grpc_resolver_factory name##_resolver_factory = { \
- &name##_factory_vtable}; \
- grpc_resolver_factory *grpc_##name##_resolver_factory_create() { \
- return &name##_resolver_factory; \
+#define DECL_FACTORY(name) \
+ static grpc_resolver *name##_factory_create_resolver( \
+ grpc_resolver_factory *factory, grpc_uri *uri, \
+ grpc_subchannel_factory *subchannel_factory) { \
+ return sockaddr_create(uri, grpc_create_pick_first_lb_policy, \
+ subchannel_factory, parse_##name); \
+ } \
+ static const grpc_resolver_factory_vtable name##_factory_vtable = { \
+ sockaddr_factory_ref, sockaddr_factory_unref, \
+ name##_factory_create_resolver, name##_get_default_authority, #name}; \
+ static grpc_resolver_factory name##_resolver_factory = { \
+ &name##_factory_vtable}; \
+ grpc_resolver_factory *grpc_##name##_resolver_factory_create() { \
+ return &name##_resolver_factory; \
}
#ifdef GPR_POSIX_SOCKET
diff --git a/src/core/client_config/resolvers/zookeeper_resolver.c b/src/core/client_config/resolvers/zookeeper_resolver.c
index acb2ba136e..da399f9954 100644
--- a/src/core/client_config/resolvers/zookeeper_resolver.c
+++ b/src/core/client_config/resolvers/zookeeper_resolver.c
@@ -467,8 +467,7 @@ static grpc_resolver *zookeeper_create(
}
static void zookeeper_plugin_init() {
- grpc_register_resolver_type("zookeeper",
- grpc_zookeeper_resolver_factory_create());
+ grpc_register_resolver_type(grpc_zookeeper_resolver_factory_create());
}
void grpc_zookeeper_register() {
@@ -483,6 +482,11 @@ static void zookeeper_factory_ref(grpc_resolver_factory *factory) {}
static void zookeeper_factory_unref(grpc_resolver_factory *factory) {}
+static char *zookeeper_factory_get_default_hostname(
+ grpc_resolver_factory *factory, grpc_uri *uri) {
+ return NULL;
+}
+
static grpc_resolver *zookeeper_factory_create_resolver(
grpc_resolver_factory *factory, grpc_uri *uri,
grpc_subchannel_factory *subchannel_factory) {
@@ -492,7 +496,8 @@ static grpc_resolver *zookeeper_factory_create_resolver(
static const grpc_resolver_factory_vtable zookeeper_factory_vtable = {
zookeeper_factory_ref, zookeeper_factory_unref,
- zookeeper_factory_create_resolver};
+ zookeeper_factory_create_resolver, zookeeper_factory_get_default_hostname,
+ "zookeeper"};
static grpc_resolver_factory zookeeper_resolver_factory = {
&zookeeper_factory_vtable};
diff --git a/src/core/profiling/basic_timers.c b/src/core/profiling/basic_timers.c
index ae37f584eb..4b6a0d2f56 100644
--- a/src/core/profiling/basic_timers.c
+++ b/src/core/profiling/basic_timers.c
@@ -36,7 +36,6 @@
#ifdef GRPC_BASIC_PROFILER
#include "src/core/profiling/timers.h"
-#include "src/core/profiling/timers_preciseclock.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
@@ -53,7 +52,7 @@ typedef enum {
} marker_type;
typedef struct grpc_timer_entry {
- grpc_precise_clock tm;
+ gpr_timespec tm;
int tag;
const char* tagstr;
marker_type type;
@@ -71,9 +70,8 @@ static void log_report() {
int i;
for (i = 0; i < count; i++) {
grpc_timer_entry* entry = &(log[i]);
- printf("GRPC_LAT_PROF " GRPC_PRECISE_CLOCK_FORMAT
- " %p %c %d(%s) %p %s %d\n",
- GRPC_PRECISE_CLOCK_PRINTF_ARGS(&entry->tm),
+ printf("GRPC_LAT_PROF %ld.%09d %p %c %d(%s) %p %s %d\n",
+ entry->tm.tv_sec, entry->tm.tv_nsec,
(void*)(gpr_intptr)gpr_thd_currentid(), entry->type, entry->tag,
entry->tagstr, entry->id, entry->file, entry->line);
}
@@ -93,7 +91,7 @@ static void grpc_timers_log_add(int tag, const char* tagstr, marker_type type,
entry = &log[count++];
- grpc_precise_clock_now(&entry->tm);
+ entry->tm = gpr_now(GPR_CLOCK_PRECISE);
entry->tag = tag;
entry->tagstr = tagstr;
entry->type = type;
diff --git a/src/core/security/client_auth_filter.c b/src/core/security/client_auth_filter.c
index 8e63978b82..f3ecfd0e60 100644
--- a/src/core/security/client_auth_filter.c
+++ b/src/core/security/client_auth_filter.c
@@ -153,7 +153,8 @@ static void send_security_metadata(grpc_call_element *elem,
}
if (channel_creds_has_md && call_creds_has_md) {
- calld->creds = grpc_composite_credentials_create(channel_creds, ctx->creds);
+ calld->creds =
+ grpc_composite_credentials_create(channel_creds, ctx->creds, NULL);
if (calld->creds == NULL) {
bubble_up_error(elem, GRPC_STATUS_INVALID_ARGUMENT,
"Incompatible credentials set on channel and call.");
diff --git a/src/core/security/credentials.c b/src/core/security/credentials.c
index 8852cab3e7..362d5f4b6f 100644
--- a/src/core/security/credentials.c
+++ b/src/core/security/credentials.c
@@ -298,8 +298,10 @@ static void ssl_build_server_config(
}
grpc_credentials *grpc_ssl_credentials_create(
- const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pair) {
+ const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pair,
+ void *reserved) {
grpc_ssl_credentials *c = gpr_malloc(sizeof(grpc_ssl_credentials));
+ GPR_ASSERT(reserved == NULL);
memset(c, 0, sizeof(grpc_ssl_credentials));
c->base.type = GRPC_CREDENTIALS_TYPE_SSL;
c->base.vtable = &ssl_vtable;
@@ -310,9 +312,11 @@ grpc_credentials *grpc_ssl_credentials_create(
grpc_server_credentials *grpc_ssl_server_credentials_create(
const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs,
- size_t num_key_cert_pairs, int force_client_auth) {
+ size_t num_key_cert_pairs, int force_client_auth, void *reserved) {
grpc_ssl_server_credentials *c =
gpr_malloc(sizeof(grpc_ssl_server_credentials));
+ GPR_ASSERT(reserved == NULL);
+ memset(c, 0, sizeof(grpc_ssl_credentials));
memset(c, 0, sizeof(grpc_ssl_server_credentials));
c->base.type = GRPC_CREDENTIALS_TYPE_SSL;
c->base.vtable = &ssl_server_vtable;
@@ -430,7 +434,8 @@ grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
}
grpc_credentials *grpc_service_account_jwt_access_credentials_create(
- const char *json_key, gpr_timespec token_lifetime) {
+ const char *json_key, gpr_timespec token_lifetime, void *reserved) {
+ GPR_ASSERT(reserved == NULL);
return grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
grpc_auth_json_key_create_from_string(json_key), token_lifetime);
}
@@ -635,9 +640,10 @@ static void compute_engine_fetch_oauth2(
metadata_req);
}
-grpc_credentials *grpc_compute_engine_credentials_create(void) {
+grpc_credentials *grpc_compute_engine_credentials_create(void *reserved) {
grpc_oauth2_token_fetcher_credentials *c =
gpr_malloc(sizeof(grpc_oauth2_token_fetcher_credentials));
+ GPR_ASSERT(reserved == NULL);
init_oauth2_token_fetcher(c, compute_engine_fetch_oauth2);
c->base.vtable = &compute_engine_vtable;
return &c->base;
@@ -693,10 +699,11 @@ static void service_account_fetch_oauth2(
}
grpc_credentials *grpc_service_account_credentials_create(
- const char *json_key, const char *scope, gpr_timespec token_lifetime) {
+ const char *json_key, const char *scope, gpr_timespec token_lifetime,
+ void *reserved) {
grpc_service_account_credentials *c;
grpc_auth_json_key key = grpc_auth_json_key_create_from_string(json_key);
-
+ GPR_ASSERT(reserved == NULL);
if (scope == NULL || (strlen(scope) == 0) ||
!grpc_auth_json_key_is_valid(&key)) {
gpr_log(GPR_ERROR,
@@ -766,7 +773,8 @@ grpc_credentials *grpc_refresh_token_credentials_create_from_auth_refresh_token(
}
grpc_credentials *grpc_refresh_token_credentials_create(
- const char *json_refresh_token) {
+ const char *json_refresh_token, void *reserved) {
+ GPR_ASSERT(reserved == NULL);
return grpc_refresh_token_credentials_create_from_auth_refresh_token(
grpc_auth_refresh_token_create_from_string(json_refresh_token));
}
@@ -867,11 +875,12 @@ static grpc_credentials_vtable access_token_vtable = {
access_token_has_request_metadata_only, access_token_get_request_metadata,
NULL};
-grpc_credentials *grpc_access_token_credentials_create(
- const char *access_token) {
+grpc_credentials *grpc_access_token_credentials_create(const char *access_token,
+ void *reserved) {
grpc_access_token_credentials *c =
gpr_malloc(sizeof(grpc_access_token_credentials));
char *token_md_value;
+ GPR_ASSERT(reserved == NULL);
memset(c, 0, sizeof(grpc_access_token_credentials));
c->base.type = GRPC_CREDENTIALS_TYPE_OAUTH2;
c->base.vtable = &access_token_vtable;
@@ -1101,12 +1110,14 @@ static grpc_credentials_array get_creds_array(grpc_credentials **creds_addr) {
}
grpc_credentials *grpc_composite_credentials_create(grpc_credentials *creds1,
- grpc_credentials *creds2) {
+ grpc_credentials *creds2,
+ void *reserved) {
size_t i;
size_t creds_array_byte_size;
grpc_credentials_array creds1_array;
grpc_credentials_array creds2_array;
grpc_composite_credentials *c;
+ GPR_ASSERT(reserved == NULL);
GPR_ASSERT(creds1 != NULL);
GPR_ASSERT(creds2 != NULL);
c = gpr_malloc(sizeof(grpc_composite_credentials));
@@ -1209,8 +1220,10 @@ static grpc_credentials_vtable iam_vtable = {
iam_get_request_metadata, NULL};
grpc_credentials *grpc_iam_credentials_create(const char *token,
- const char *authority_selector) {
+ const char *authority_selector,
+ void *reserved) {
grpc_iam_credentials *c;
+ GPR_ASSERT(reserved == NULL);
GPR_ASSERT(token != NULL);
GPR_ASSERT(authority_selector != NULL);
c = gpr_malloc(sizeof(grpc_iam_credentials));
diff --git a/src/core/security/google_default_credentials.c b/src/core/security/google_default_credentials.c
index 3631de867a..f9aa5187ce 100644
--- a/src/core/security/google_default_credentials.c
+++ b/src/core/security/google_default_credentials.c
@@ -194,7 +194,7 @@ grpc_credentials *grpc_google_default_credentials_create(void) {
int need_compute_engine_creds = is_stack_running_on_compute_engine();
compute_engine_detection_done = 1;
if (need_compute_engine_creds) {
- result = grpc_compute_engine_credentials_create();
+ result = grpc_compute_engine_credentials_create(NULL);
}
}
@@ -202,9 +202,9 @@ end:
if (!serving_cached_credentials && result != NULL) {
/* Blend with default ssl credentials and add a global reference so that it
can be cached and re-served. */
- grpc_credentials *ssl_creds = grpc_ssl_credentials_create(NULL, NULL);
+ grpc_credentials *ssl_creds = grpc_ssl_credentials_create(NULL, NULL, NULL);
default_credentials = grpc_credentials_ref(
- grpc_composite_credentials_create(ssl_creds, result));
+ grpc_composite_credentials_create(ssl_creds, result, NULL));
GPR_ASSERT(default_credentials != NULL);
grpc_credentials_unref(ssl_creds);
grpc_credentials_unref(result);
diff --git a/src/core/support/log_win32.c b/src/core/support/log_win32.c
index 629781da8a..b68239f8f5 100644
--- a/src/core/support/log_win32.c
+++ b/src/core/support/log_win32.c
@@ -81,10 +81,18 @@ void gpr_log(const char *file, int line, gpr_log_severity severity,
/* Simple starter implementation */
void gpr_default_log(gpr_log_func_args *args) {
+ char *final_slash;
+ const char *display_file;
char time_buffer[64];
gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
struct tm tm;
+ final_slash = strrchr(args->file, '\\');
+ if (final_slash == NULL)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
if (localtime_s(&tm, &now.tv_sec)) {
strcpy(time_buffer, "error:localtime");
} else if (0 ==
@@ -94,7 +102,7 @@ void gpr_default_log(gpr_log_func_args *args) {
fprintf(stderr, "%s%s.%09u %5lu %s:%d] %s\n",
gpr_log_severity_string(args->severity), time_buffer,
- (int)(now.tv_nsec), GetCurrentThreadId(), args->file, args->line,
+ (int)(now.tv_nsec), GetCurrentThreadId(), display_file, args->line,
args->message);
}
diff --git a/src/core/support/time_posix.c b/src/core/support/time_posix.c
index 841485c4b4..a274400243 100644
--- a/src/core/support/time_posix.c
+++ b/src/core/support/time_posix.c
@@ -32,6 +32,7 @@
*/
#include <grpc/support/port_platform.h>
+#include <src/core/support/time_precise.h>
#ifdef GPR_POSIX_TIME
@@ -66,8 +67,14 @@ void gpr_time_init(void) {}
gpr_timespec gpr_now(gpr_clock_type clock) {
struct timespec now;
GPR_ASSERT(clock != GPR_TIMESPAN);
- clock_gettime(clockid_for_gpr_clock[clock], &now);
- return gpr_from_timespec(now, clock);
+ if (clock == GPR_CLOCK_PRECISE) {
+ gpr_timespec ret;
+ gpr_precise_clock_now(&ret);
+ return ret;
+ } else {
+ clock_gettime(clockid_for_gpr_clock[clock], &now);
+ return gpr_from_timespec(now, clock);
+ }
}
#else
/* For some reason Apple's OSes haven't implemented clock_gettime. */
@@ -104,6 +111,9 @@ gpr_timespec gpr_now(gpr_clock_type clock) {
now.tv_sec = now_dbl * 1e-9;
now.tv_nsec = now_dbl - now.tv_sec * 1e9;
break;
+ case GPR_CLOCK_PRECISE:
+ gpr_precise_clock_now(&now);
+ break;
case GPR_TIMESPAN:
abort();
}
diff --git a/src/core/profiling/timers_preciseclock.h b/src/core/support/time_precise.h
index 5c251b47e6..574ebb8448 100644
--- a/src/core/profiling/timers_preciseclock.h
+++ b/src/core/support/time_precise.h
@@ -31,65 +31,63 @@
*
*/
-#ifndef GRPC_CORE_PROFILING_TIMERS_PRECISECLOCK_H
-#define GRPC_CORE_PROFILING_TIMERS_PRECISECLOCK_H
+#ifndef GRPC_CORE_SUPPORT_TIME_PRECISE_H_
+#define GRPC_CORE_SUPPORT_TIME_PRECISE_H_
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
#include <stdio.h>
#ifdef GRPC_TIMERS_RDTSC
-typedef long long int grpc_precise_clock;
#if defined(__i386__)
-static void grpc_precise_clock_now(grpc_precise_clock *clk) {
- grpc_precise_clock ret;
+static void gpr_get_cycle_counter(long long int *clk) {
+ long long int ret;
__asm__ volatile("rdtsc" : "=A"(ret));
*clk = ret;
}
// ----------------------------------------------------------------
#elif defined(__x86_64__) || defined(__amd64__)
-static void grpc_precise_clock_now(grpc_precise_clock *clk) {
+static void gpr_get_cycle_counter(long long int *clk) {
unsigned long long low, high;
__asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
*clk = (high << 32) | low;
}
#endif
+
static gpr_once precise_clock_init = GPR_ONCE_INIT;
-static double cycles_per_second = 0.0;
-static void grpc_precise_clock_init() {
+static long long cycles_per_second = 0;
+static void gpr_precise_clock_init() {
time_t start = time(NULL);
- grpc_precise_clock start_time;
- grpc_precise_clock end_time;
+ gpr_precise_clock start_cycle;
+ gpr_precise_clock end_cycle;
while (time(NULL) == start)
;
- grpc_precise_clock_now(&start_time);
+ gpr_get_cycle_counter(&start_cycle);
while (time(NULL) == start + 1)
;
- grpc_precise_clock_now(&end_time);
- cycles_per_second = end_time - start_time;
+ gpr_get_cycle_counter(&end_cycle);
+ cycles_per_second = end_cycle - start_cycle;
}
+
static double grpc_precise_clock_scaling_factor() {
gpr_once_init(&precise_clock_init, grpc_precise_clock_init);
return 1e6 / cycles_per_second;
}
-#define GRPC_PRECISE_CLOCK_FORMAT "%f"
-#define GRPC_PRECISE_CLOCK_PRINTF_ARGS(clk) \
- (*(clk)*grpc_precise_clock_scaling_factor())
-#else
-typedef struct grpc_precise_clock grpc_precise_clock;
-struct grpc_precise_clock {
- gpr_timespec clock;
-};
-static void grpc_precise_clock_now(grpc_precise_clock* clk) {
- clk->clock = gpr_now(GPR_CLOCK_REALTIME);
+
+static void gpr_precise_clock_now(gpr_timespec *clk) {
+ long long int counter;
+ gpr_get_cycle_counter(&counter);
+ clk->clock = GPR_CLOCK_REALTIME;
+ clk->tv_sec = counter / cycles_per_second;
+ clk->tv_nsec = counter % cycles_per_second;
}
-#define GRPC_PRECISE_CLOCK_FORMAT "%ld.%09d"
-#define GRPC_PRECISE_CLOCK_PRINTF_ARGS(clk) \
- (clk)->clock.tv_sec, (clk)->clock.tv_nsec
-static void grpc_precise_clock_print(const grpc_precise_clock* clk, FILE* fp) {
- fprintf(fp, "%ld.%09d", clk->clock.tv_sec, clk->clock.tv_nsec);
+
+#else /* GRPC_TIMERS_RDTSC */
+static void gpr_precise_clock_now(gpr_timespec *clk) {
+ *clk = gpr_now(GPR_CLOCK_REALTIME);
+ clk->clock_type = GPR_CLOCK_PRECISE;
}
#endif /* GRPC_TIMERS_RDTSC */
-#endif /* GRPC_CORE_PROFILING_TIMERS_PRECISECLOCK_H */
+#endif /* GRPC_CORE_SUPPORT_TIME_PRECISE_ */
diff --git a/src/core/support/time_win32.c b/src/core/support/time_win32.c
index 7f64c80e27..f794855429 100644
--- a/src/core/support/time_win32.c
+++ b/src/core/support/time_win32.c
@@ -38,6 +38,7 @@
#ifdef GPR_WIN32
#include <grpc/support/time.h>
+#include <src/core/support/time_precise.h>
#include <sys/timeb.h>
static LARGE_INTEGER g_start_time;
@@ -68,6 +69,9 @@ gpr_timespec gpr_now(gpr_clock_type clock) {
now_tv.tv_sec = (time_t)now_dbl;
now_tv.tv_nsec = (int)((now_dbl - (double)now_tv.tv_sec) * 1e9);
break;
+ case GPR_CLOCK_PRECISE:
+ gpr_precise_clock_now(&now_tv);
+ break;
}
return now_tv;
}
diff --git a/src/core/surface/call.c b/src/core/surface/call.c
index 33f277da46..4426bbbce9 100644
--- a/src/core/surface/call.c
+++ b/src/core/surface/call.c
@@ -1046,10 +1046,11 @@ static int prepare_application_metadata(grpc_call *call, size_t count,
(const gpr_uint8 *)md->value,
md->value_length, 1);
if (!grpc_mdstr_is_legal_header(l->md->key)) {
- gpr_log(GPR_ERROR, "attempt to send invalid metadata key");
+ gpr_log(GPR_ERROR, "attempt to send invalid metadata key: %s",
+ grpc_mdstr_as_c_string(l->md->key));
return 0;
} else if (!grpc_mdstr_is_bin_suffixed(l->md->key) &&
- !grpc_mdstr_is_legal_header(l->md->value)) {
+ !grpc_mdstr_is_legal_nonbin_header(l->md->value)) {
gpr_log(GPR_ERROR, "attempt to send invalid metadata value");
return 0;
}
diff --git a/src/core/surface/channel.c b/src/core/surface/channel.c
index e50251566d..586402e21c 100644
--- a/src/core/surface/channel.c
+++ b/src/core/surface/channel.c
@@ -40,6 +40,7 @@
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
+#include "src/core/client_config/resolver_registry.h"
#include "src/core/iomgr/iomgr.h"
#include "src/core/support/string.h"
#include "src/core/surface/call.h"
@@ -70,6 +71,7 @@ struct grpc_channel {
grpc_mdstr *grpc_message_string;
grpc_mdstr *path_string;
grpc_mdstr *authority_string;
+ grpc_mdelem *default_authority;
/** mdelem for grpc-status: 0 thru grpc-status: 2 */
grpc_mdelem *grpc_status_elem[NUM_CACHED_STATUS_ELEMS];
@@ -134,10 +136,47 @@ grpc_channel *grpc_channel_create_from_filters(
} else {
channel->max_message_length = args->args[i].value.integer;
}
+ } else if (0 == strcmp(args->args[i].key, GRPC_ARG_DEFAULT_AUTHORITY)) {
+ if (args->args[i].type != GRPC_ARG_STRING) {
+ gpr_log(GPR_ERROR, "%s: must be an string",
+ GRPC_ARG_DEFAULT_AUTHORITY);
+ } else {
+ if (channel->default_authority) {
+ /* setting this takes precedence over anything else */
+ GRPC_MDELEM_UNREF(channel->default_authority);
+ }
+ channel->default_authority = grpc_mdelem_from_strings(
+ mdctx, ":authority", args->args[i].value.string);
+ }
+ } else if (0 ==
+ strcmp(args->args[i].key, GRPC_SSL_TARGET_NAME_OVERRIDE_ARG)) {
+ if (args->args[i].type != GRPC_ARG_STRING) {
+ gpr_log(GPR_ERROR, "%s: must be an string",
+ GRPC_SSL_TARGET_NAME_OVERRIDE_ARG);
+ } else {
+ if (channel->default_authority) {
+ /* other ways of setting this (notably ssl) take precedence */
+ gpr_log(GPR_ERROR, "%s: default host already set some other way",
+ GRPC_ARG_DEFAULT_AUTHORITY);
+ } else {
+ channel->default_authority = grpc_mdelem_from_strings(
+ mdctx, ":authority", args->args[i].value.string);
+ }
+ }
}
}
}
+ if (channel->is_client && channel->default_authority == NULL &&
+ target != NULL) {
+ char *default_authority = grpc_get_default_authority(target);
+ if (default_authority) {
+ channel->default_authority = grpc_mdelem_from_strings(
+ channel->metadata_context, ":authority", default_authority);
+ }
+ gpr_free(default_authority);
+ }
+
grpc_channel_stack_init(filters, num_filters, channel, args,
channel->metadata_context,
CHANNEL_STACK_FROM_CHANNEL(channel));
@@ -161,6 +200,8 @@ static grpc_call *grpc_channel_create_call_internal(
send_metadata[num_metadata++] = path_mdelem;
if (authority_mdelem != NULL) {
send_metadata[num_metadata++] = authority_mdelem;
+ } else if (channel->default_authority != NULL) {
+ send_metadata[num_metadata++] = GRPC_MDELEM_REF(channel->default_authority);
}
return grpc_call_create(channel, parent_call, propagation_mask, cq, NULL,
@@ -251,6 +292,9 @@ static void destroy_channel(void *p, int ok) {
}
gpr_free(rc);
}
+ if (channel->default_authority != NULL) {
+ GRPC_MDELEM_UNREF(channel->default_authority);
+ }
grpc_mdctx_unref(channel->metadata_context);
gpr_mu_destroy(&channel->registered_call_mu);
gpr_free(channel->target);
diff --git a/src/core/surface/init.c b/src/core/surface/init.c
index d9044549f2..0d48cd42d7 100644
--- a/src/core/surface/init.c
+++ b/src/core/surface/init.c
@@ -86,11 +86,11 @@ void grpc_init(void) {
if (++g_initializations == 1) {
gpr_time_init();
grpc_resolver_registry_init("dns:///");
- grpc_register_resolver_type("dns", grpc_dns_resolver_factory_create());
- grpc_register_resolver_type("ipv4", grpc_ipv4_resolver_factory_create());
- grpc_register_resolver_type("ipv6", grpc_ipv6_resolver_factory_create());
+ grpc_register_resolver_type(grpc_dns_resolver_factory_create());
+ grpc_register_resolver_type(grpc_ipv4_resolver_factory_create());
+ grpc_register_resolver_type(grpc_ipv6_resolver_factory_create());
#ifdef GPR_POSIX_SOCKET
- grpc_register_resolver_type("unix", grpc_unix_resolver_factory_create());
+ grpc_register_resolver_type(grpc_unix_resolver_factory_create());
#endif
grpc_register_tracer("channel", &grpc_trace_channel);
grpc_register_tracer("surface", &grpc_surface_trace);
diff --git a/src/core/surface/secure_channel_create.c b/src/core/surface/secure_channel_create.c
index eccee24698..35b60bdbef 100644
--- a/src/core/surface/secure_channel_create.c
+++ b/src/core/surface/secure_channel_create.c
@@ -185,7 +185,8 @@ static const grpc_subchannel_factory_vtable subchannel_factory_vtable = {
- perform handshakes */
grpc_channel *grpc_secure_channel_create(grpc_credentials *creds,
const char *target,
- const grpc_channel_args *args) {
+ const grpc_channel_args *args,
+ void *reserved) {
grpc_channel *channel;
grpc_arg connector_arg;
grpc_channel_args *args_copy;
@@ -198,6 +199,7 @@ grpc_channel *grpc_secure_channel_create(grpc_credentials *creds,
const grpc_channel_filter *filters[MAX_FILTERS];
int n = 0;
+ GPR_ASSERT(reserved == NULL);
if (grpc_find_security_connector_in_args(args) != NULL) {
gpr_log(GPR_ERROR, "Cannot set security context in channel args.");
return grpc_lame_client_channel_create(
diff --git a/src/core/transport/chttp2/stream_lists.c b/src/core/transport/chttp2/stream_lists.c
index 38c6052f9c..781db7b0d6 100644
--- a/src/core/transport/chttp2/stream_lists.c
+++ b/src/core/transport/chttp2/stream_lists.c
@@ -177,8 +177,10 @@ int grpc_chttp2_list_pop_writable_stream(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_GLOBAL(transport_global), &stream,
GRPC_CHTTP2_LIST_WRITABLE);
- *stream_global = &stream->global;
- *stream_writing = &stream->writing;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ *stream_writing = &stream->writing;
+ }
return r;
}
@@ -210,7 +212,9 @@ int grpc_chttp2_list_pop_writing_stream(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_WRITING(transport_writing), &stream,
GRPC_CHTTP2_LIST_WRITING);
- *stream_writing = &stream->writing;
+ if (r != 0) {
+ *stream_writing = &stream->writing;
+ }
return r;
}
@@ -230,8 +234,10 @@ int grpc_chttp2_list_pop_written_stream(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_WRITING(transport_writing), &stream,
GRPC_CHTTP2_LIST_WRITTEN);
- *stream_global = &stream->global;
- *stream_writing = &stream->writing;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ *stream_writing = &stream->writing;
+ }
return r;
}
@@ -251,8 +257,10 @@ int grpc_chttp2_list_pop_parsing_seen_stream(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_PARSING(transport_parsing), &stream,
GRPC_CHTTP2_LIST_PARSING_SEEN);
- *stream_global = &stream->global;
- *stream_parsing = &stream->parsing;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ *stream_parsing = &stream->parsing;
+ }
return r;
}
@@ -270,7 +278,9 @@ int grpc_chttp2_list_pop_waiting_for_concurrency(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_GLOBAL(transport_global), &stream,
GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY);
- *stream_global = &stream->global;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ }
return r;
}
@@ -288,7 +298,9 @@ int grpc_chttp2_list_pop_closed_waiting_for_parsing(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_GLOBAL(transport_global), &stream,
GRPC_CHTTP2_LIST_CLOSED_WAITING_FOR_PARSING);
- *stream_global = &stream->global;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ }
return r;
}
@@ -306,7 +318,9 @@ int grpc_chttp2_list_pop_cancelled_waiting_for_writing(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_GLOBAL(transport_global), &stream,
GRPC_CHTTP2_LIST_CANCELLED_WAITING_FOR_WRITING);
- *stream_global = &stream->global;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ }
return r;
}
@@ -326,8 +340,10 @@ int grpc_chttp2_list_pop_incoming_window_updated(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_GLOBAL(transport_global), &stream,
GRPC_CHTTP2_LIST_INCOMING_WINDOW_UPDATED);
- *stream_global = &stream->global;
- *stream_parsing = &stream->parsing;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ *stream_parsing = &stream->parsing;
+ }
return r;
}
@@ -353,7 +369,9 @@ int grpc_chttp2_list_pop_read_write_state_changed(
grpc_chttp2_stream *stream;
int r = stream_list_pop(TRANSPORT_FROM_GLOBAL(transport_global), &stream,
GRPC_CHTTP2_LIST_READ_WRITE_STATE_CHANGED);
- *stream_global = &stream->global;
+ if (r != 0) {
+ *stream_global = &stream->global;
+ }
return r;
}
diff --git a/src/core/transport/metadata.c b/src/core/transport/metadata.c
index f92e87e9dd..61638764a6 100644
--- a/src/core/transport/metadata.c
+++ b/src/core/transport/metadata.c
@@ -681,16 +681,34 @@ void grpc_mdctx_locked_mdelem_unref(grpc_mdctx *ctx,
void grpc_mdctx_unlock(grpc_mdctx *ctx) { unlock(ctx); }
-int grpc_mdstr_is_legal_header(grpc_mdstr *s) {
- /* TODO(ctiller): consider caching this, or computing it on construction */
+static int conforms_to(grpc_mdstr *s, const gpr_uint8 *legal_bits) {
const gpr_uint8 *p = GPR_SLICE_START_PTR(s->slice);
const gpr_uint8 *e = GPR_SLICE_END_PTR(s->slice);
for (; p != e; p++) {
- if (*p < 32 || *p > 126) return 0;
+ int idx = *p;
+ int byte = idx / 8;
+ int bit = idx % 8;
+ if ((legal_bits[byte] & (1 << bit)) == 0) return 0;
}
return 1;
}
+int grpc_mdstr_is_legal_header(grpc_mdstr *s) {
+ static const gpr_uint8 legal_header_bits[256 / 8] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0xff, 0x03, 0x00, 0x00, 0x00,
+ 0x80, 0xfe, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ return conforms_to(s, legal_header_bits);
+}
+
+int grpc_mdstr_is_legal_nonbin_header(grpc_mdstr *s) {
+ static const gpr_uint8 legal_header_bits[256 / 8] = {
+ 0x00, 0x00, 0x00, 0x00, 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ return conforms_to(s, legal_header_bits);
+}
+
int grpc_mdstr_is_bin_suffixed(grpc_mdstr *s) {
/* TODO(ctiller): consider caching this */
return grpc_is_binary_header((const char *)GPR_SLICE_START_PTR(s->slice),
diff --git a/src/core/transport/metadata.h b/src/core/transport/metadata.h
index a7af49ba55..eb17747be7 100644
--- a/src/core/transport/metadata.h
+++ b/src/core/transport/metadata.h
@@ -154,6 +154,7 @@ void grpc_mdelem_unref(grpc_mdelem *md);
const char *grpc_mdstr_as_c_string(grpc_mdstr *s);
int grpc_mdstr_is_legal_header(grpc_mdstr *s);
+int grpc_mdstr_is_legal_nonbin_header(grpc_mdstr *s);
int grpc_mdstr_is_bin_suffixed(grpc_mdstr *s);
/* Batch mode metadata functions.
diff --git a/src/cpp/client/create_channel.cc b/src/cpp/client/create_channel.cc
index 8c571cbbaa..1dac960017 100644
--- a/src/cpp/client/create_channel.cc
+++ b/src/cpp/client/create_channel.cc
@@ -44,6 +44,11 @@ namespace grpc {
class ChannelArguments;
std::shared_ptr<Channel> CreateChannel(
+ const grpc::string& target, const std::shared_ptr<Credentials>& creds) {
+ return CreateCustomChannel(target, creds, ChannelArguments());
+}
+
+std::shared_ptr<Channel> CreateCustomChannel(
const grpc::string& target, const std::shared_ptr<Credentials>& creds,
const ChannelArguments& args) {
ChannelArguments cp_args = args;
@@ -57,4 +62,5 @@ std::shared_ptr<Channel> CreateChannel(
NULL, GRPC_STATUS_INVALID_ARGUMENT,
"Invalid credentials."));
}
+
} // namespace grpc
diff --git a/src/cpp/client/secure_credentials.cc b/src/cpp/client/secure_credentials.cc
index f368f2590a..e0642469b4 100644
--- a/src/cpp/client/secure_credentials.cc
+++ b/src/cpp/client/secure_credentials.cc
@@ -46,7 +46,8 @@ std::shared_ptr<grpc::Channel> SecureCredentials::CreateChannel(
args.SetChannelArgs(&channel_args);
return CreateChannelInternal(
args.GetSslTargetNameOverride(),
- grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args));
+ grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args,
+ nullptr));
}
bool SecureCredentials::ApplyToCall(grpc_call* call) {
@@ -75,14 +76,14 @@ std::shared_ptr<Credentials> SslCredentials(
grpc_credentials* c_creds = grpc_ssl_credentials_create(
options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
- options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair);
+ options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr);
return WrapCredentials(c_creds);
}
// Builds credentials for use when running in GCE
std::shared_ptr<Credentials> ComputeEngineCredentials() {
GrpcLibrary init; // To call grpc_init().
- return WrapCredentials(grpc_compute_engine_credentials_create());
+ return WrapCredentials(grpc_compute_engine_credentials_create(nullptr));
}
// Builds service account credentials.
@@ -99,7 +100,7 @@ std::shared_ptr<Credentials> ServiceAccountCredentials(
gpr_timespec lifetime =
gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN);
return WrapCredentials(grpc_service_account_credentials_create(
- json_key.c_str(), scope.c_str(), lifetime));
+ json_key.c_str(), scope.c_str(), lifetime, nullptr));
}
// Builds JWT credentials.
@@ -114,15 +115,15 @@ std::shared_ptr<Credentials> ServiceAccountJWTAccessCredentials(
gpr_timespec lifetime =
gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN);
return WrapCredentials(grpc_service_account_jwt_access_credentials_create(
- json_key.c_str(), lifetime));
+ json_key.c_str(), lifetime, nullptr));
}
// Builds refresh token credentials.
std::shared_ptr<Credentials> RefreshTokenCredentials(
const grpc::string& json_refresh_token) {
GrpcLibrary init; // To call grpc_init().
- return WrapCredentials(
- grpc_refresh_token_credentials_create(json_refresh_token.c_str()));
+ return WrapCredentials(grpc_refresh_token_credentials_create(
+ json_refresh_token.c_str(), nullptr));
}
// Builds access token credentials.
@@ -130,7 +131,7 @@ std::shared_ptr<Credentials> AccessTokenCredentials(
const grpc::string& access_token) {
GrpcLibrary init; // To call grpc_init().
return WrapCredentials(
- grpc_access_token_credentials_create(access_token.c_str()));
+ grpc_access_token_credentials_create(access_token.c_str(), nullptr));
}
// Builds IAM credentials.
@@ -139,7 +140,7 @@ std::shared_ptr<Credentials> IAMCredentials(
const grpc::string& authority_selector) {
GrpcLibrary init; // To call grpc_init().
return WrapCredentials(grpc_iam_credentials_create(
- authorization_token.c_str(), authority_selector.c_str()));
+ authorization_token.c_str(), authority_selector.c_str(), nullptr));
}
// Combines two credentials objects into a composite credentials.
@@ -154,7 +155,7 @@ std::shared_ptr<Credentials> CompositeCredentials(
SecureCredentials* s2 = creds2->AsSecureCredentials();
if (s1 && s2) {
return WrapCredentials(grpc_composite_credentials_create(
- s1->GetRawCreds(), s2->GetRawCreds()));
+ s1->GetRawCreds(), s2->GetRawCreds(), nullptr));
}
return nullptr;
}
diff --git a/src/cpp/common/auth_property_iterator.cc b/src/cpp/common/auth_property_iterator.cc
index 5ccf8cf72c..fa6da9d7a8 100644
--- a/src/cpp/common/auth_property_iterator.cc
+++ b/src/cpp/common/auth_property_iterator.cc
@@ -77,9 +77,9 @@ bool AuthPropertyIterator::operator!=(const AuthPropertyIterator& rhs) const {
}
const AuthProperty AuthPropertyIterator::operator*() {
- return std::make_pair<grpc::string, grpc::string>(
- grpc::string(property_->name),
- grpc::string(property_->value, property_->value_length));
+ return std::pair<grpc::string_ref, grpc::string_ref>(
+ property_->name,
+ grpc::string_ref(property_->value, property_->value_length));
}
} // namespace grpc
diff --git a/src/cpp/common/call.cc b/src/cpp/common/call.cc
index 16aa2c9fb9..5b87c2a806 100644
--- a/src/cpp/common/call.cc
+++ b/src/cpp/common/call.cc
@@ -41,13 +41,14 @@
namespace grpc {
-void FillMetadataMap(grpc_metadata_array* arr,
- std::multimap<grpc::string, grpc::string>* metadata) {
+void FillMetadataMap(
+ grpc_metadata_array* arr,
+ std::multimap<grpc::string_ref, grpc::string_ref>* metadata) {
for (size_t i = 0; i < arr->count; i++) {
// TODO(yangg) handle duplicates?
- metadata->insert(std::pair<grpc::string, grpc::string>(
- arr->metadata[i].key,
- grpc::string(arr->metadata[i].value, arr->metadata[i].value_length)));
+ metadata->insert(std::pair<grpc::string_ref, grpc::string_ref>(
+ arr->metadata[i].key, grpc::string_ref(arr->metadata[i].value,
+ arr->metadata[i].value_length)));
}
grpc_metadata_array_destroy(arr);
grpc_metadata_array_init(arr);
diff --git a/src/cpp/common/secure_auth_context.cc b/src/cpp/common/secure_auth_context.cc
index 87d7bab75c..b18a8537c9 100644
--- a/src/cpp/common/secure_auth_context.cc
+++ b/src/cpp/common/secure_auth_context.cc
@@ -41,15 +41,16 @@ SecureAuthContext::SecureAuthContext(grpc_auth_context* ctx) : ctx_(ctx) {}
SecureAuthContext::~SecureAuthContext() { grpc_auth_context_release(ctx_); }
-std::vector<grpc::string> SecureAuthContext::GetPeerIdentity() const {
+std::vector<grpc::string_ref> SecureAuthContext::GetPeerIdentity() const {
if (!ctx_) {
- return std::vector<grpc::string>();
+ return std::vector<grpc::string_ref>();
}
grpc_auth_property_iterator iter = grpc_auth_context_peer_identity(ctx_);
- std::vector<grpc::string> identity;
+ std::vector<grpc::string_ref> identity;
const grpc_auth_property* property = nullptr;
while ((property = grpc_auth_property_iterator_next(&iter))) {
- identity.push_back(grpc::string(property->value, property->value_length));
+ identity.push_back(
+ grpc::string_ref(property->value, property->value_length));
}
return identity;
}
@@ -62,17 +63,17 @@ grpc::string SecureAuthContext::GetPeerIdentityPropertyName() const {
return name == nullptr ? "" : name;
}
-std::vector<grpc::string> SecureAuthContext::FindPropertyValues(
+std::vector<grpc::string_ref> SecureAuthContext::FindPropertyValues(
const grpc::string& name) const {
if (!ctx_) {
- return std::vector<grpc::string>();
+ return std::vector<grpc::string_ref>();
}
grpc_auth_property_iterator iter =
grpc_auth_context_find_properties_by_name(ctx_, name.c_str());
const grpc_auth_property* property = nullptr;
- std::vector<grpc::string> values;
+ std::vector<grpc::string_ref> values;
while ((property = grpc_auth_property_iterator_next(&iter))) {
- values.push_back(grpc::string(property->value, property->value_length));
+ values.push_back(grpc::string_ref(property->value, property->value_length));
}
return values;
}
diff --git a/src/cpp/common/secure_auth_context.h b/src/cpp/common/secure_auth_context.h
index 01b7126189..7f622b890b 100644
--- a/src/cpp/common/secure_auth_context.h
+++ b/src/cpp/common/secure_auth_context.h
@@ -46,12 +46,12 @@ class SecureAuthContext GRPC_FINAL : public AuthContext {
~SecureAuthContext() GRPC_OVERRIDE;
- std::vector<grpc::string> GetPeerIdentity() const GRPC_OVERRIDE;
+ std::vector<grpc::string_ref> GetPeerIdentity() const GRPC_OVERRIDE;
grpc::string GetPeerIdentityPropertyName() const GRPC_OVERRIDE;
- std::vector<grpc::string> FindPropertyValues(const grpc::string& name) const
- GRPC_OVERRIDE;
+ std::vector<grpc::string_ref> FindPropertyValues(
+ const grpc::string& name) const GRPC_OVERRIDE;
AuthPropertyIterator begin() const GRPC_OVERRIDE;
diff --git a/src/cpp/server/secure_server_credentials.cc b/src/cpp/server/secure_server_credentials.cc
index f203cf7f49..5bce9ca8b2 100644
--- a/src/cpp/server/secure_server_credentials.cc
+++ b/src/cpp/server/secure_server_credentials.cc
@@ -52,7 +52,7 @@ std::shared_ptr<ServerCredentials> SslServerCredentials(
grpc_server_credentials* c_creds = grpc_ssl_server_credentials_create(
options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
&pem_key_cert_pairs[0], pem_key_cert_pairs.size(),
- options.force_client_auth);
+ options.force_client_auth, nullptr);
return std::shared_ptr<ServerCredentials>(
new SecureServerCredentials(c_creds));
}
diff --git a/src/cpp/server/server.cc b/src/cpp/server/server.cc
index 66cd27cc33..bb83c7d887 100644
--- a/src/cpp/server/server.cc
+++ b/src/cpp/server/server.cc
@@ -439,11 +439,12 @@ Server::BaseAsyncRequest::~BaseAsyncRequest() {}
bool Server::BaseAsyncRequest::FinalizeResult(void** tag, bool* status) {
if (*status) {
for (size_t i = 0; i < initial_metadata_array_.count; i++) {
- context_->client_metadata_.insert(std::make_pair(
- grpc::string(initial_metadata_array_.metadata[i].key),
- grpc::string(initial_metadata_array_.metadata[i].value,
- initial_metadata_array_.metadata[i].value +
- initial_metadata_array_.metadata[i].value_length)));
+ context_->client_metadata_.insert(
+ std::pair<grpc::string_ref, grpc::string_ref>(
+ initial_metadata_array_.metadata[i].key,
+ grpc::string_ref(
+ initial_metadata_array_.metadata[i].value,
+ initial_metadata_array_.metadata[i].value_length)));
}
}
grpc_metadata_array_destroy(&initial_metadata_array_);
diff --git a/src/cpp/server/server_context.cc b/src/cpp/server/server_context.cc
index acc163d6b5..8193e70660 100644
--- a/src/cpp/server/server_context.cc
+++ b/src/cpp/server/server_context.cc
@@ -136,10 +136,9 @@ ServerContext::ServerContext(gpr_timespec deadline, grpc_metadata* metadata,
cq_(nullptr),
sent_initial_metadata_(false) {
for (size_t i = 0; i < metadata_count; i++) {
- client_metadata_.insert(std::make_pair(
- grpc::string(metadata[i].key),
- grpc::string(metadata[i].value,
- metadata[i].value + metadata[i].value_length)));
+ client_metadata_.insert(std::pair<grpc::string_ref, grpc::string_ref>(
+ metadata[i].key,
+ grpc::string_ref(metadata[i].value, metadata[i].value_length)));
}
}
diff --git a/src/cpp/util/string_ref.cc b/src/cpp/util/string_ref.cc
index 8483e8c2ee..9adc092013 100644
--- a/src/cpp/util/string_ref.cc
+++ b/src/cpp/util/string_ref.cc
@@ -39,7 +39,7 @@
namespace grpc {
-constexpr size_t string_ref::npos;
+const size_t string_ref::npos;
string_ref& string_ref::operator=(const string_ref& rhs) {
data_ = rhs.data_;
@@ -80,7 +80,7 @@ size_t string_ref::find(string_ref s) const {
}
size_t string_ref::find(char c) const {
- auto it = std::find_if(cbegin(), cend(), [c](char cc) { return cc == c; });
+ auto it = std::find(cbegin(), cend(), c);
return it == cend() ? npos : std::distance(cbegin(), it);
}
@@ -108,4 +108,8 @@ bool operator>=(string_ref x, string_ref y) {
return x.compare(y) >= 0;
}
+std::ostream& operator<<(std::ostream& out, const string_ref& string) {
+ return out << grpc::string(string.begin(), string.end());
+}
+
} // namespace grpc
diff --git a/src/csharp/.gitignore b/src/csharp/.gitignore
index 48365e32a5..deac55029e 100644
--- a/src/csharp/.gitignore
+++ b/src/csharp/.gitignore
@@ -4,6 +4,9 @@ StyleCop.Cache
test-results
packages
Grpc.v12.suo
+Grpc.sdf
+
TestResult.xml
/TestResults
+.vs/
*.nupkg
diff --git a/src/csharp/Grpc.Core.Tests/Grpc.Core.Tests.csproj b/src/csharp/Grpc.Core.Tests/Grpc.Core.Tests.csproj
index b571fe9025..f730936062 100644
--- a/src/csharp/Grpc.Core.Tests/Grpc.Core.Tests.csproj
+++ b/src/csharp/Grpc.Core.Tests/Grpc.Core.Tests.csproj
@@ -64,6 +64,7 @@
<Link>Version.cs</Link>
</Compile>
<Compile Include="ClientBaseTest.cs" />
+ <Compile Include="MarshallingErrorsTest.cs" />
<Compile Include="ShutdownTest.cs" />
<Compile Include="Internal\AsyncCallTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
diff --git a/src/csharp/Grpc.Core.Tests/MarshallingErrorsTest.cs b/src/csharp/Grpc.Core.Tests/MarshallingErrorsTest.cs
new file mode 100644
index 0000000000..83707e0c6d
--- /dev/null
+++ b/src/csharp/Grpc.Core.Tests/MarshallingErrorsTest.cs
@@ -0,0 +1,176 @@
+#region Copyright notice and license
+
+// Copyright 2015, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+
+using Grpc.Core;
+using Grpc.Core.Internal;
+using Grpc.Core.Utils;
+using NUnit.Framework;
+
+namespace Grpc.Core.Tests
+{
+ public class MarshallingErrorsTest
+ {
+ const string Host = "127.0.0.1";
+
+ MockServiceHelper helper;
+ Server server;
+ Channel channel;
+
+ [SetUp]
+ public void Init()
+ {
+ var marshaller = new Marshaller<string>(
+ (str) =>
+ {
+ if (str == "UNSERIALIZABLE_VALUE")
+ {
+ // Google.Protobuf throws exception inherited from IOException
+ throw new IOException("Error serializing the message.");
+ }
+ return System.Text.Encoding.UTF8.GetBytes(str);
+ },
+ (payload) =>
+ {
+ var s = System.Text.Encoding.UTF8.GetString(payload);
+ if (s == "UNPARSEABLE_VALUE")
+ {
+ // Google.Protobuf throws exception inherited from IOException
+ throw new IOException("Error parsing the message.");
+ }
+ return s;
+ });
+ helper = new MockServiceHelper(Host, marshaller);
+ server = helper.GetServer();
+ server.Start();
+ channel = helper.GetChannel();
+ }
+
+ [TearDown]
+ public void Cleanup()
+ {
+ channel.ShutdownAsync().Wait();
+ server.ShutdownAsync().Wait();
+ }
+
+ [Test]
+ public void ResponseParsingError_UnaryResponse()
+ {
+ helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
+ {
+ return Task.FromResult("UNPARSEABLE_VALUE");
+ });
+
+ var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "REQUEST"));
+ Assert.AreEqual(StatusCode.Internal, ex.Status.StatusCode);
+ }
+
+ [Test]
+ public void ResponseParsingError_StreamingResponse()
+ {
+ helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) =>
+ {
+ await responseStream.WriteAsync("UNPARSEABLE_VALUE");
+ await Task.Delay(10000);
+ });
+
+ var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "REQUEST");
+ var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext());
+ Assert.AreEqual(StatusCode.Internal, ex.Status.StatusCode);
+ }
+
+ [Test]
+ public void RequestParsingError_UnaryRequest()
+ {
+ helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
+ {
+ return Task.FromResult("RESPONSE");
+ });
+
+ var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "UNPARSEABLE_VALUE"));
+ // Spec doesn't define the behavior. With the current implementation server handler throws exception which results in StatusCode.Unknown.
+ Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
+ }
+
+ [Test]
+ public async Task RequestParsingError_StreamingRequest()
+ {
+ helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
+ {
+ Assert.Throws<IOException>(async () => await requestStream.MoveNext());
+ return "RESPONSE";
+ });
+
+ var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall());
+ await call.RequestStream.WriteAsync("UNPARSEABLE_VALUE");
+
+ Assert.AreEqual("RESPONSE", await call);
+ }
+
+ [Test]
+ public void RequestSerializationError_BlockingUnary()
+ {
+ Assert.Throws<IOException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "UNSERIALIZABLE_VALUE"));
+ }
+
+ [Test]
+ public void RequestSerializationError_AsyncUnary()
+ {
+ Assert.Throws<IOException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "UNSERIALIZABLE_VALUE"));
+ }
+
+ [Test]
+ public async Task RequestSerializationError_ClientStreaming()
+ {
+ helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
+ {
+ CollectionAssert.AreEqual(new [] {"A", "B"}, await requestStream.ToListAsync());
+ return "RESPONSE";
+ });
+ var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall());
+ await call.RequestStream.WriteAsync("A");
+ Assert.Throws<IOException>(async () => await call.RequestStream.WriteAsync("UNSERIALIZABLE_VALUE"));
+ await call.RequestStream.WriteAsync("B");
+ await call.RequestStream.CompleteAsync();
+
+ Assert.AreEqual("RESPONSE", await call);
+ }
+ }
+}
diff --git a/src/csharp/Grpc.Core.Tests/MetadataTest.cs b/src/csharp/Grpc.Core.Tests/MetadataTest.cs
index c00f945d6a..ddeb7d0926 100644
--- a/src/csharp/Grpc.Core.Tests/MetadataTest.cs
+++ b/src/csharp/Grpc.Core.Tests/MetadataTest.cs
@@ -75,6 +75,17 @@ namespace Grpc.Core.Tests
}
[Test]
+ public void AsciiEntry_KeyValidity()
+ {
+ new Metadata.Entry("ABC", "XYZ");
+ new Metadata.Entry("0123456789abc", "XYZ");
+ new Metadata.Entry("-abc", "XYZ");
+ new Metadata.Entry("a_bc_", "XYZ");
+ Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc[", "xyz"));
+ Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc/", "xyz"));
+ }
+
+ [Test]
public void Entry_ConstructionPreconditions()
{
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry(null, "xyz"));
diff --git a/src/csharp/Grpc.Core.Tests/MockServiceHelper.cs b/src/csharp/Grpc.Core.Tests/MockServiceHelper.cs
index bb69648d8b..765732c768 100644
--- a/src/csharp/Grpc.Core.Tests/MockServiceHelper.cs
+++ b/src/csharp/Grpc.Core.Tests/MockServiceHelper.cs
@@ -50,37 +50,14 @@ namespace Grpc.Core.Tests
{
public const string ServiceName = "tests.Test";
- public static readonly Method<string, string> UnaryMethod = new Method<string, string>(
- MethodType.Unary,
- ServiceName,
- "Unary",
- Marshallers.StringMarshaller,
- Marshallers.StringMarshaller);
-
- public static readonly Method<string, string> ClientStreamingMethod = new Method<string, string>(
- MethodType.ClientStreaming,
- ServiceName,
- "ClientStreaming",
- Marshallers.StringMarshaller,
- Marshallers.StringMarshaller);
-
- public static readonly Method<string, string> ServerStreamingMethod = new Method<string, string>(
- MethodType.ServerStreaming,
- ServiceName,
- "ServerStreaming",
- Marshallers.StringMarshaller,
- Marshallers.StringMarshaller);
-
- public static readonly Method<string, string> DuplexStreamingMethod = new Method<string, string>(
- MethodType.DuplexStreaming,
- ServiceName,
- "DuplexStreaming",
- Marshallers.StringMarshaller,
- Marshallers.StringMarshaller);
-
readonly string host;
readonly ServerServiceDefinition serviceDefinition;
+ readonly Method<string, string> unaryMethod;
+ readonly Method<string, string> clientStreamingMethod;
+ readonly Method<string, string> serverStreamingMethod;
+ readonly Method<string, string> duplexStreamingMethod;
+
UnaryServerMethod<string, string> unaryHandler;
ClientStreamingServerMethod<string, string> clientStreamingHandler;
ServerStreamingServerMethod<string, string> serverStreamingHandler;
@@ -89,15 +66,44 @@ namespace Grpc.Core.Tests
Server server;
Channel channel;
- public MockServiceHelper(string host = null)
+ public MockServiceHelper(string host = null, Marshaller<string> marshaller = null)
{
this.host = host ?? "localhost";
+ marshaller = marshaller ?? Marshallers.StringMarshaller;
+
+ unaryMethod = new Method<string, string>(
+ MethodType.Unary,
+ ServiceName,
+ "Unary",
+ marshaller,
+ marshaller);
+
+ clientStreamingMethod = new Method<string, string>(
+ MethodType.ClientStreaming,
+ ServiceName,
+ "ClientStreaming",
+ marshaller,
+ marshaller);
+
+ serverStreamingMethod = new Method<string, string>(
+ MethodType.ServerStreaming,
+ ServiceName,
+ "ServerStreaming",
+ marshaller,
+ marshaller);
+
+ duplexStreamingMethod = new Method<string, string>(
+ MethodType.DuplexStreaming,
+ ServiceName,
+ "DuplexStreaming",
+ marshaller,
+ marshaller);
serviceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName)
- .AddMethod(UnaryMethod, (request, context) => unaryHandler(request, context))
- .AddMethod(ClientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context))
- .AddMethod(ServerStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context))
- .AddMethod(DuplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context))
+ .AddMethod(unaryMethod, (request, context) => unaryHandler(request, context))
+ .AddMethod(clientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context))
+ .AddMethod(serverStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context))
+ .AddMethod(duplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context))
.Build();
var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own.");
@@ -155,22 +161,22 @@ namespace Grpc.Core.Tests
public CallInvocationDetails<string, string> CreateUnaryCall(CallOptions options = default(CallOptions))
{
- return new CallInvocationDetails<string, string>(channel, UnaryMethod, options);
+ return new CallInvocationDetails<string, string>(channel, unaryMethod, options);
}
public CallInvocationDetails<string, string> CreateClientStreamingCall(CallOptions options = default(CallOptions))
{
- return new CallInvocationDetails<string, string>(channel, ClientStreamingMethod, options);
+ return new CallInvocationDetails<string, string>(channel, clientStreamingMethod, options);
}
public CallInvocationDetails<string, string> CreateServerStreamingCall(CallOptions options = default(CallOptions))
{
- return new CallInvocationDetails<string, string>(channel, ServerStreamingMethod, options);
+ return new CallInvocationDetails<string, string>(channel, serverStreamingMethod, options);
}
public CallInvocationDetails<string, string> CreateDuplexStreamingCall(CallOptions options = default(CallOptions))
{
- return new CallInvocationDetails<string, string>(channel, DuplexStreamingMethod, options);
+ return new CallInvocationDetails<string, string>(channel, duplexStreamingMethod, options);
}
public string Host
diff --git a/src/csharp/Grpc.Core/Internal/AsyncCall.cs b/src/csharp/Grpc.Core/Internal/AsyncCall.cs
index be5d611a53..e3b00781c6 100644
--- a/src/csharp/Grpc.Core/Internal/AsyncCall.cs
+++ b/src/csharp/Grpc.Core/Internal/AsyncCall.cs
@@ -322,6 +322,11 @@ namespace Grpc.Core.Internal
details.Channel.RemoveCallReference(this);
}
+ protected override bool IsClient
+ {
+ get { return true; }
+ }
+
private void Initialize(CompletionQueueSafeHandle cq)
{
var call = CreateNativeCall(cq);
@@ -376,9 +381,17 @@ namespace Grpc.Core.Internal
/// </summary>
private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
{
+ TResponse msg = default(TResponse);
+ var deserializeException = success ? TryDeserialize(receivedMessage, out msg) : null;
+
lock (myLock)
{
finished = true;
+
+ if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
+ {
+ receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
+ }
finishedStatus = receivedStatus;
ReleaseResourcesIfPossible();
@@ -394,10 +407,6 @@ namespace Grpc.Core.Internal
return;
}
- // TODO: handle deserialization error
- TResponse msg;
- TryDeserialize(receivedMessage, out msg);
-
unaryResponseTcs.SetResult(msg);
}
diff --git a/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs b/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs
index 4d20394644..3e2c57c9b5 100644
--- a/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs
+++ b/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs
@@ -33,10 +33,12 @@
using System;
using System.Diagnostics;
+using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
+
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
@@ -50,6 +52,7 @@ namespace Grpc.Core.Internal
internal abstract class AsyncCallBase<TWrite, TRead>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
+ protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message.");
readonly Func<TWrite, byte[]> serializer;
readonly Func<byte[], TRead> deserializer;
@@ -100,11 +103,10 @@ namespace Grpc.Core.Internal
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
- public void CancelWithStatus(Status status)
+ protected void CancelWithStatus(Status status)
{
lock (myLock)
{
- Preconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
@@ -177,6 +179,11 @@ namespace Grpc.Core.Internal
return false;
}
+ protected abstract bool IsClient
+ {
+ get;
+ }
+
private void ReleaseResources()
{
if (call != null)
@@ -224,33 +231,31 @@ namespace Grpc.Core.Internal
return serializer(msg);
}
- protected bool TrySerialize(TWrite msg, out byte[] payload)
+ protected Exception TrySerialize(TWrite msg, out byte[] payload)
{
try
{
payload = serializer(msg);
- return true;
+ return null;
}
catch (Exception e)
{
- Logger.Error(e, "Exception occured while trying to serialize message");
payload = null;
- return false;
+ return e;
}
}
- protected bool TryDeserialize(byte[] payload, out TRead msg)
+ protected Exception TryDeserialize(byte[] payload, out TRead msg)
{
try
{
msg = deserializer(payload);
- return true;
+ return null;
}
catch (Exception e)
{
- Logger.Error(e, "Exception occured while trying to deserialize message.");
msg = default(TRead);
- return false;
+ return e;
}
}
@@ -319,6 +324,9 @@ namespace Grpc.Core.Internal
/// </summary>
protected void HandleReadFinished(bool success, byte[] receivedMessage)
{
+ TRead msg = default(TRead);
+ var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null;
+
AsyncCompletionDelegate<TRead> origCompletionDelegate = null;
lock (myLock)
{
@@ -331,23 +339,23 @@ namespace Grpc.Core.Internal
readingDone = true;
}
+ if (deserializeException != null && IsClient)
+ {
+ readingDone = true;
+ CancelWithStatus(DeserializeResponseFailureStatus);
+ }
+
ReleaseResourcesIfPossible();
}
- // TODO: handle the case when error occured...
+ // TODO: handle the case when success==false
- if (receivedMessage != null)
- {
- // TODO: handle deserialization error
- TRead msg;
- TryDeserialize(receivedMessage, out msg);
-
- FireCompletion(origCompletionDelegate, msg, null);
- }
- else
+ if (deserializeException != null && !IsClient)
{
- FireCompletion(origCompletionDelegate, default(TRead), null);
+ FireCompletion(origCompletionDelegate, default(TRead), new IOException("Failed to deserialize request message.", deserializeException));
+ return;
}
+ FireCompletion(origCompletionDelegate, msg, null);
}
}
} \ No newline at end of file
diff --git a/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs b/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs
index 5c47251030..46ca459349 100644
--- a/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs
+++ b/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs
@@ -169,6 +169,11 @@ namespace Grpc.Core.Internal
}
}
+ protected override bool IsClient
+ {
+ get { return false; }
+ }
+
protected override void CheckReadingAllowed()
{
base.CheckReadingAllowed();
diff --git a/src/csharp/Grpc.Core/Marshaller.cs b/src/csharp/Grpc.Core/Marshaller.cs
index f38cb0863f..3493d2d38f 100644
--- a/src/csharp/Grpc.Core/Marshaller.cs
+++ b/src/csharp/Grpc.Core/Marshaller.cs
@@ -39,7 +39,7 @@ namespace Grpc.Core
/// <summary>
/// Encapsulates the logic for serializing and deserializing messages.
/// </summary>
- public struct Marshaller<T>
+ public class Marshaller<T>
{
readonly Func<T, byte[]> serializer;
readonly Func<byte[], T> deserializer;
diff --git a/src/csharp/Grpc.Core/Metadata.cs b/src/csharp/Grpc.Core/Metadata.cs
index 99fe0b5478..21bdf4f114 100644
--- a/src/csharp/Grpc.Core/Metadata.cs
+++ b/src/csharp/Grpc.Core/Metadata.cs
@@ -33,8 +33,10 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
+using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
+using System.Text.RegularExpressions;
using Grpc.Core.Utils;
@@ -188,6 +190,7 @@ namespace Grpc.Core
public struct Entry
{
private static readonly Encoding Encoding = Encoding.ASCII;
+ private static readonly Regex ValidKeyRegex = new Regex("^[a-z0-9_-]+$");
readonly string key;
readonly string value;
@@ -320,7 +323,10 @@ namespace Grpc.Core
private static string NormalizeKey(string key)
{
- return Preconditions.CheckNotNull(key, "key").ToLower();
+ var normalized = Preconditions.CheckNotNull(key, "key").ToLower(CultureInfo.InvariantCulture);
+ Preconditions.CheckArgument(ValidKeyRegex.IsMatch(normalized),
+ "Metadata entry key not valid. Keys can only contain lowercase alphanumeric characters, underscores and hyphens.");
+ return normalized;
}
}
}
diff --git a/src/csharp/Grpc.Core/VersionInfo.cs b/src/csharp/Grpc.Core/VersionInfo.cs
index b6dbd3b49c..eda821bc31 100644
--- a/src/csharp/Grpc.Core/VersionInfo.cs
+++ b/src/csharp/Grpc.Core/VersionInfo.cs
@@ -39,8 +39,8 @@ namespace Grpc.Core
public static class VersionInfo
{
/// <summary>
- /// Current version of gRPC
+ /// Current version of gRPC C#
/// </summary>
- public const string CurrentVersion = "0.6.1";
+ public const string CurrentVersion = "0.7.0";
}
}
diff --git a/src/csharp/Grpc.Examples.MathClient/MathClient.cs b/src/csharp/Grpc.Examples.MathClient/MathClient.cs
index abd95cb905..01e4a80bab 100644
--- a/src/csharp/Grpc.Examples.MathClient/MathClient.cs
+++ b/src/csharp/Grpc.Examples.MathClient/MathClient.cs
@@ -33,7 +33,7 @@ using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core;
-namespace math
+namespace Math
{
class MathClient
{
diff --git a/src/csharp/Grpc.Examples.MathServer/MathServer.cs b/src/csharp/Grpc.Examples.MathServer/MathServer.cs
index 26bef646ec..6e974a0871 100644
--- a/src/csharp/Grpc.Examples.MathServer/MathServer.cs
+++ b/src/csharp/Grpc.Examples.MathServer/MathServer.cs
@@ -34,7 +34,7 @@ using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core;
-namespace math
+namespace Math
{
class MainClass
{
diff --git a/src/csharp/Grpc.Examples.Tests/Grpc.Examples.Tests.csproj b/src/csharp/Grpc.Examples.Tests/Grpc.Examples.Tests.csproj
index 9a8f780b24..c4c1ee6d00 100644
--- a/src/csharp/Grpc.Examples.Tests/Grpc.Examples.Tests.csproj
+++ b/src/csharp/Grpc.Examples.Tests/Grpc.Examples.Tests.csproj
@@ -37,13 +37,14 @@
<AssemblyOriginatorKeyFile>C:\keys\Grpc.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
+ <Reference Include="Google.Protobuf, Version=3.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
+ </Reference>
<Reference Include="nunit.framework">
<HintPath>..\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
- <Reference Include="Google.ProtocolBuffers">
- <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.521\lib\net40\Google.ProtocolBuffers.dll</HintPath>
- </Reference>
<Reference Include="System.Interactive.Async, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Ix-Async.1.2.3\lib\net45\System.Interactive.Async.dll</HintPath>
diff --git a/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs b/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs
index 36c1c947bd..e2975b5da9 100644
--- a/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs
+++ b/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs
@@ -40,7 +40,7 @@ using Grpc.Core;
using Grpc.Core.Utils;
using NUnit.Framework;
-namespace math.Tests
+namespace Math.Tests
{
/// <summary>
/// Math client talks to local math server.
@@ -75,7 +75,7 @@ namespace math.Tests
[Test]
public void Div1()
{
- DivReply response = client.Div(new DivArgs.Builder { Dividend = 10, Divisor = 3 }.Build());
+ DivReply response = client.Div(new DivArgs { Dividend = 10, Divisor = 3 });
Assert.AreEqual(3, response.Quotient);
Assert.AreEqual(1, response.Remainder);
}
@@ -83,7 +83,7 @@ namespace math.Tests
[Test]
public void Div2()
{
- DivReply response = client.Div(new DivArgs.Builder { Dividend = 0, Divisor = 1 }.Build());
+ DivReply response = client.Div(new DivArgs { Dividend = 0, Divisor = 1 });
Assert.AreEqual(0, response.Quotient);
Assert.AreEqual(0, response.Remainder);
}
@@ -91,14 +91,14 @@ namespace math.Tests
[Test]
public void DivByZero()
{
- var ex = Assert.Throws<RpcException>(() => client.Div(new DivArgs.Builder { Dividend = 0, Divisor = 0 }.Build()));
+ var ex = Assert.Throws<RpcException>(() => client.Div(new DivArgs { Dividend = 0, Divisor = 0 }));
Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
}
[Test]
public async Task DivAsync()
{
- DivReply response = await client.DivAsync(new DivArgs.Builder { Dividend = 10, Divisor = 3 }.Build());
+ DivReply response = await client.DivAsync(new DivArgs { Dividend = 10, Divisor = 3 });
Assert.AreEqual(3, response.Quotient);
Assert.AreEqual(1, response.Remainder);
}
@@ -106,7 +106,7 @@ namespace math.Tests
[Test]
public async Task Fib()
{
- using (var call = client.Fib(new FibArgs.Builder { Limit = 6 }.Build()))
+ using (var call = client.Fib(new FibArgs { Limit = 6 }))
{
var responses = await call.ResponseStream.ToListAsync();
CollectionAssert.AreEqual(new List<long> { 1, 1, 2, 3, 5, 8 },
@@ -119,8 +119,7 @@ namespace math.Tests
{
var cts = new CancellationTokenSource();
- using (var call = client.Fib(new FibArgs.Builder { Limit = 0 }.Build(),
- cancellationToken: cts.Token))
+ using (var call = client.Fib(new FibArgs { Limit = 0 }, cancellationToken: cts.Token))
{
List<long> responses = new List<long>();
@@ -147,7 +146,7 @@ namespace math.Tests
[Test]
public async Task FibWithDeadline()
{
- using (var call = client.Fib(new FibArgs.Builder { Limit = 0 }.Build(),
+ using (var call = client.Fib(new FibArgs { Limit = 0 },
deadline: DateTime.UtcNow.AddMilliseconds(500)))
{
var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.ToListAsync());
@@ -163,8 +162,7 @@ namespace math.Tests
{
using (var call = client.Sum())
{
- var numbers = new List<long> { 10, 20, 30 }.ConvertAll(
- n => Num.CreateBuilder().SetNum_(n).Build());
+ var numbers = new List<long> { 10, 20, 30 }.ConvertAll(n => new Num { Num_ = n });
await call.RequestStream.WriteAllAsync(numbers);
var result = await call.ResponseAsync;
@@ -177,9 +175,9 @@ namespace math.Tests
{
var divArgsList = new List<DivArgs>
{
- new DivArgs.Builder { Dividend = 10, Divisor = 3 }.Build(),
- new DivArgs.Builder { Dividend = 100, Divisor = 21 }.Build(),
- new DivArgs.Builder { Dividend = 7, Divisor = 2 }.Build()
+ new DivArgs { Dividend = 10, Divisor = 3 },
+ new DivArgs { Dividend = 100, Divisor = 21 },
+ new DivArgs { Dividend = 7, Divisor = 2 }
};
using (var call = client.DivMany())
diff --git a/src/csharp/Grpc.Examples.Tests/packages.config b/src/csharp/Grpc.Examples.Tests/packages.config
index cc6e9af40f..7266fa1763 100644
--- a/src/csharp/Grpc.Examples.Tests/packages.config
+++ b/src/csharp/Grpc.Examples.Tests/packages.config
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
- <package id="Google.ProtocolBuffers" version="2.4.1.521" targetFramework="net45" />
+ <package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
<package id="NUnit" version="2.6.4" targetFramework="net45" />
</packages> \ No newline at end of file
diff --git a/src/csharp/Grpc.Examples/Grpc.Examples.csproj b/src/csharp/Grpc.Examples/Grpc.Examples.csproj
index c1aa40500e..55462e02fd 100644
--- a/src/csharp/Grpc.Examples/Grpc.Examples.csproj
+++ b/src/csharp/Grpc.Examples/Grpc.Examples.csproj
@@ -37,11 +37,12 @@
<AssemblyOriginatorKeyFile>C:\keys\Grpc.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
+ <Reference Include="Google.Protobuf, Version=3.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
+ </Reference>
<Reference Include="System" />
<Reference Include="System.Data.Linq" />
- <Reference Include="Google.ProtocolBuffers">
- <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.521\lib\net40\Google.ProtocolBuffers.dll</HintPath>
- </Reference>
<Reference Include="System.Interactive.Async">
<HintPath>..\packages\Ix-Async.1.2.3\lib\net45\System.Interactive.Async.dll</HintPath>
</Reference>
diff --git a/src/csharp/Grpc.Examples/Math.cs b/src/csharp/Grpc.Examples/Math.cs
index 75b1e9dbc2..d0e1ee8aae 100644
--- a/src/csharp/Grpc.Examples/Math.cs
+++ b/src/csharp/Grpc.Examples/Math.cs
@@ -1,80 +1,46 @@
-// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: math.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
-using pb = global::Google.ProtocolBuffers;
-using pbc = global::Google.ProtocolBuffers.Collections;
-using pbd = global::Google.ProtocolBuffers.Descriptors;
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
-namespace math {
+namespace Math {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Math {
- #region Extension registration
- public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
- }
- #endregion
- #region Static variables
- internal static pbd::MessageDescriptor internal__static_math_DivArgs__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::math.DivArgs, global::math.DivArgs.Builder> internal__static_math_DivArgs__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_math_DivReply__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::math.DivReply, global::math.DivReply.Builder> internal__static_math_DivReply__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_math_FibArgs__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::math.FibArgs, global::math.FibArgs.Builder> internal__static_math_FibArgs__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_math_Num__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::math.Num, global::math.Num.Builder> internal__static_math_Num__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_math_FibReply__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::math.FibReply, global::math.FibReply.Builder> internal__static_math_FibReply__FieldAccessorTable;
- #endregion
#region Descriptor
- public static pbd::FileDescriptor Descriptor {
+ public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
- private static pbd::FileDescriptor descriptor;
+ private static pbr::FileDescriptor descriptor;
static Math() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "CgptYXRoLnByb3RvEgRtYXRoIiwKB0RpdkFyZ3MSEAoIZGl2aWRlbmQYASAB",
- "KAMSDwoHZGl2aXNvchgCIAEoAyIvCghEaXZSZXBseRIQCghxdW90aWVudBgB",
- "IAEoAxIRCglyZW1haW5kZXIYAiABKAMiGAoHRmliQXJncxINCgVsaW1pdBgB",
- "IAEoAyISCgNOdW0SCwoDbnVtGAEgASgDIhkKCEZpYlJlcGx5Eg0KBWNvdW50",
- "GAEgASgDMqQBCgRNYXRoEiYKA0RpdhINLm1hdGguRGl2QXJncxoOLm1hdGgu",
- "RGl2UmVwbHkiABIuCgdEaXZNYW55Eg0ubWF0aC5EaXZBcmdzGg4ubWF0aC5E",
- "aXZSZXBseSIAKAEwARIjCgNGaWISDS5tYXRoLkZpYkFyZ3MaCS5tYXRoLk51",
- "bSIAMAESHwoDU3VtEgkubWF0aC5OdW0aCS5tYXRoLk51bSIAKAE="));
- pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
- descriptor = root;
- internal__static_math_DivArgs__Descriptor = Descriptor.MessageTypes[0];
- internal__static_math_DivArgs__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::math.DivArgs, global::math.DivArgs.Builder>(internal__static_math_DivArgs__Descriptor,
- new string[] { "Dividend", "Divisor", });
- internal__static_math_DivReply__Descriptor = Descriptor.MessageTypes[1];
- internal__static_math_DivReply__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::math.DivReply, global::math.DivReply.Builder>(internal__static_math_DivReply__Descriptor,
- new string[] { "Quotient", "Remainder", });
- internal__static_math_FibArgs__Descriptor = Descriptor.MessageTypes[2];
- internal__static_math_FibArgs__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::math.FibArgs, global::math.FibArgs.Builder>(internal__static_math_FibArgs__Descriptor,
- new string[] { "Limit", });
- internal__static_math_Num__Descriptor = Descriptor.MessageTypes[3];
- internal__static_math_Num__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::math.Num, global::math.Num.Builder>(internal__static_math_Num__Descriptor,
- new string[] { "Num_", });
- internal__static_math_FibReply__Descriptor = Descriptor.MessageTypes[4];
- internal__static_math_FibReply__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::math.FibReply, global::math.FibReply.Builder>(internal__static_math_FibReply__Descriptor,
- new string[] { "Count", });
- pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
- RegisterAllExtensions(registry);
- return registry;
- };
- pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
- new pbd::FileDescriptor[] {
- }, assigner);
+ "CgptYXRoLnByb3RvEgRtYXRoIiwKB0RpdkFyZ3MSEAoIZGl2aWRlbmQYASAB",
+ "KAMSDwoHZGl2aXNvchgCIAEoAyIvCghEaXZSZXBseRIQCghxdW90aWVudBgB",
+ "IAEoAxIRCglyZW1haW5kZXIYAiABKAMiGAoHRmliQXJncxINCgVsaW1pdBgB",
+ "IAEoAyISCgNOdW0SCwoDbnVtGAEgASgDIhkKCEZpYlJlcGx5Eg0KBWNvdW50",
+ "GAEgASgDMqQBCgRNYXRoEiYKA0RpdhINLm1hdGguRGl2QXJncxoOLm1hdGgu",
+ "RGl2UmVwbHkiABIuCgdEaXZNYW55Eg0ubWF0aC5EaXZBcmdzGg4ubWF0aC5E",
+ "aXZSZXBseSIAKAEwARIjCgNGaWISDS5tYXRoLkZpYkFyZ3MaCS5tYXRoLk51",
+ "bSIAMAESHwoDU3VtEgkubWF0aC5OdW0aCS5tYXRoLk51bSIAKAFiBnByb3Rv",
+ "Mw=="));
+ descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
+ new pbr::FileDescriptor[] { },
+ new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
+ new pbr::GeneratedCodeInfo(typeof(global::Math.DivArgs), new[]{ "Dividend", "Divisor" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Math.DivReply), new[]{ "Quotient", "Remainder" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Math.FibArgs), new[]{ "Limit" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Math.Num), new[]{ "Num_" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Math.FibReply), new[]{ "Count" }, null, null, null)
+ }));
}
#endregion
@@ -82,1448 +48,567 @@ namespace math {
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class DivArgs : pb::GeneratedMessage<DivArgs, DivArgs.Builder> {
- private DivArgs() { }
- private static readonly DivArgs defaultInstance = new DivArgs().MakeReadOnly();
- private static readonly string[] _divArgsFieldNames = new string[] { "dividend", "divisor" };
- private static readonly uint[] _divArgsFieldTags = new uint[] { 8, 16 };
- public static DivArgs DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class DivArgs : pb::IMessage<DivArgs> {
+ private static readonly pb::MessageParser<DivArgs> _parser = new pb::MessageParser<DivArgs>(() => new DivArgs());
+ public static pb::MessageParser<DivArgs> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Math.Proto.Math.Descriptor.MessageTypes[0]; }
}
- public override DivArgs DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override DivArgs ThisMessage {
- get { return this; }
+ public DivArgs() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::math.Proto.Math.internal__static_math_DivArgs__Descriptor; }
+ partial void OnConstruction();
+
+ public DivArgs(DivArgs other) : this() {
+ dividend_ = other.dividend_;
+ divisor_ = other.divisor_;
}
- protected override pb::FieldAccess.FieldAccessorTable<DivArgs, DivArgs.Builder> InternalFieldAccessors {
- get { return global::math.Proto.Math.internal__static_math_DivArgs__FieldAccessorTable; }
+ public DivArgs Clone() {
+ return new DivArgs(this);
}
public const int DividendFieldNumber = 1;
- private bool hasDividend;
private long dividend_;
- public bool HasDividend {
- get { return hasDividend; }
- }
public long Dividend {
get { return dividend_; }
+ set {
+ dividend_ = value;
+ }
}
public const int DivisorFieldNumber = 2;
- private bool hasDivisor;
private long divisor_;
- public bool HasDivisor {
- get { return hasDivisor; }
- }
public long Divisor {
get { return divisor_; }
+ set {
+ divisor_ = value;
+ }
}
- public override bool IsInitialized {
- get {
- return true;
- }
+ public override bool Equals(object other) {
+ return Equals(other as DivArgs);
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _divArgsFieldNames;
- if (hasDividend) {
- output.WriteInt64(1, field_names[0], Dividend);
+ public bool Equals(DivArgs other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
- if (hasDivisor) {
- output.WriteInt64(2, field_names[1], Divisor);
+ if (ReferenceEquals(other, this)) {
+ return true;
}
- UnknownFields.WriteTo(output);
+ if (Dividend != other.Dividend) return false;
+ if (Divisor != other.Divisor) return false;
+ return true;
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasDividend) {
- size += pb::CodedOutputStream.ComputeInt64Size(1, Dividend);
- }
- if (hasDivisor) {
- size += pb::CodedOutputStream.ComputeInt64Size(2, Divisor);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
- }
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Dividend != 0L) hash ^= Dividend.GetHashCode();
+ if (Divisor != 0L) hash ^= Divisor.GetHashCode();
+ return hash;
}
- public static DivArgs ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static DivArgs ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static DivArgs ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static DivArgs ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static DivArgs ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static DivArgs ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- public static DivArgs ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static DivArgs ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static DivArgs ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static DivArgs ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private DivArgs MakeReadOnly() {
- return this;
- }
-
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(DivArgs prototype) {
- return new Builder(prototype);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<DivArgs, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(DivArgs cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private DivArgs result;
-
- private DivArgs PrepareBuilder() {
- if (resultIsReadOnly) {
- DivArgs original = result;
- result = new DivArgs();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
- public override bool IsInitialized {
- get { return result.IsInitialized; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Dividend != 0L) {
+ output.WriteRawTag(8);
+ output.WriteInt64(Dividend);
}
-
- protected override DivArgs MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::math.DivArgs.Descriptor; }
+ if (Divisor != 0L) {
+ output.WriteRawTag(16);
+ output.WriteInt64(Divisor);
}
+ }
- public override DivArgs DefaultInstanceForType {
- get { return global::math.DivArgs.DefaultInstance; }
+ public int CalculateSize() {
+ int size = 0;
+ if (Dividend != 0L) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(Dividend);
}
-
- public override DivArgs BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ if (Divisor != 0L) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(Divisor);
}
+ return size;
+ }
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is DivArgs) {
- return MergeFrom((DivArgs) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ public void MergeFrom(DivArgs other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(DivArgs other) {
- if (other == global::math.DivArgs.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasDividend) {
- Dividend = other.Dividend;
- }
- if (other.HasDivisor) {
- Divisor = other.Divisor;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
+ if (other.Dividend != 0L) {
+ Dividend = other.Dividend;
}
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ if (other.Divisor != 0L) {
+ Divisor = other.Divisor;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_divArgsFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _divArgsFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Dividend = input.ReadInt64();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- result.hasDividend = input.ReadInt64(ref result.dividend_);
- break;
- }
- case 16: {
- result.hasDivisor = input.ReadInt64(ref result.divisor_);
- break;
- }
+ case 16: {
+ Divisor = input.ReadInt64();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasDividend {
- get { return result.hasDividend; }
- }
- public long Dividend {
- get { return result.Dividend; }
- set { SetDividend(value); }
}
- public Builder SetDividend(long value) {
- PrepareBuilder();
- result.hasDividend = true;
- result.dividend_ = value;
- return this;
- }
- public Builder ClearDividend() {
- PrepareBuilder();
- result.hasDividend = false;
- result.dividend_ = 0L;
- return this;
- }
-
- public bool HasDivisor {
- get { return result.hasDivisor; }
- }
- public long Divisor {
- get { return result.Divisor; }
- set { SetDivisor(value); }
- }
- public Builder SetDivisor(long value) {
- PrepareBuilder();
- result.hasDivisor = true;
- result.divisor_ = value;
- return this;
- }
- public Builder ClearDivisor() {
- PrepareBuilder();
- result.hasDivisor = false;
- result.divisor_ = 0L;
- return this;
- }
- }
- static DivArgs() {
- object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class DivReply : pb::GeneratedMessage<DivReply, DivReply.Builder> {
- private DivReply() { }
- private static readonly DivReply defaultInstance = new DivReply().MakeReadOnly();
- private static readonly string[] _divReplyFieldNames = new string[] { "quotient", "remainder" };
- private static readonly uint[] _divReplyFieldTags = new uint[] { 8, 16 };
- public static DivReply DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class DivReply : pb::IMessage<DivReply> {
+ private static readonly pb::MessageParser<DivReply> _parser = new pb::MessageParser<DivReply>(() => new DivReply());
+ public static pb::MessageParser<DivReply> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Math.Proto.Math.Descriptor.MessageTypes[1]; }
}
- public override DivReply DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override DivReply ThisMessage {
- get { return this; }
+ public DivReply() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::math.Proto.Math.internal__static_math_DivReply__Descriptor; }
+ partial void OnConstruction();
+
+ public DivReply(DivReply other) : this() {
+ quotient_ = other.quotient_;
+ remainder_ = other.remainder_;
}
- protected override pb::FieldAccess.FieldAccessorTable<DivReply, DivReply.Builder> InternalFieldAccessors {
- get { return global::math.Proto.Math.internal__static_math_DivReply__FieldAccessorTable; }
+ public DivReply Clone() {
+ return new DivReply(this);
}
public const int QuotientFieldNumber = 1;
- private bool hasQuotient;
private long quotient_;
- public bool HasQuotient {
- get { return hasQuotient; }
- }
public long Quotient {
get { return quotient_; }
+ set {
+ quotient_ = value;
+ }
}
public const int RemainderFieldNumber = 2;
- private bool hasRemainder;
private long remainder_;
- public bool HasRemainder {
- get { return hasRemainder; }
- }
public long Remainder {
get { return remainder_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ remainder_ = value;
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _divReplyFieldNames;
- if (hasQuotient) {
- output.WriteInt64(1, field_names[0], Quotient);
- }
- if (hasRemainder) {
- output.WriteInt64(2, field_names[1], Remainder);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as DivReply);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasQuotient) {
- size += pb::CodedOutputStream.ComputeInt64Size(1, Quotient);
- }
- if (hasRemainder) {
- size += pb::CodedOutputStream.ComputeInt64Size(2, Remainder);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(DivReply other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Quotient != other.Quotient) return false;
+ if (Remainder != other.Remainder) return false;
+ return true;
}
- public static DivReply ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static DivReply ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static DivReply ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static DivReply ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static DivReply ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static DivReply ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static DivReply ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static DivReply ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static DivReply ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static DivReply ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private DivReply MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Quotient != 0L) hash ^= Quotient.GetHashCode();
+ if (Remainder != 0L) hash ^= Remainder.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(DivReply prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<DivReply, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(DivReply cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private DivReply result;
-
- private DivReply PrepareBuilder() {
- if (resultIsReadOnly) {
- DivReply original = result;
- result = new DivReply();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override DivReply MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Quotient != 0L) {
+ output.WriteRawTag(8);
+ output.WriteInt64(Quotient);
}
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::math.DivReply.Descriptor; }
+ if (Remainder != 0L) {
+ output.WriteRawTag(16);
+ output.WriteInt64(Remainder);
}
+ }
- public override DivReply DefaultInstanceForType {
- get { return global::math.DivReply.DefaultInstance; }
+ public int CalculateSize() {
+ int size = 0;
+ if (Quotient != 0L) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(Quotient);
}
-
- public override DivReply BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ if (Remainder != 0L) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(Remainder);
}
+ return size;
+ }
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is DivReply) {
- return MergeFrom((DivReply) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ public void MergeFrom(DivReply other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(DivReply other) {
- if (other == global::math.DivReply.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasQuotient) {
- Quotient = other.Quotient;
- }
- if (other.HasRemainder) {
- Remainder = other.Remainder;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
+ if (other.Quotient != 0L) {
+ Quotient = other.Quotient;
}
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ if (other.Remainder != 0L) {
+ Remainder = other.Remainder;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_divReplyFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _divReplyFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Quotient = input.ReadInt64();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- result.hasQuotient = input.ReadInt64(ref result.quotient_);
- break;
- }
- case 16: {
- result.hasRemainder = input.ReadInt64(ref result.remainder_);
- break;
- }
+ case 16: {
+ Remainder = input.ReadInt64();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasQuotient {
- get { return result.hasQuotient; }
- }
- public long Quotient {
- get { return result.Quotient; }
- set { SetQuotient(value); }
- }
- public Builder SetQuotient(long value) {
- PrepareBuilder();
- result.hasQuotient = true;
- result.quotient_ = value;
- return this;
- }
- public Builder ClearQuotient() {
- PrepareBuilder();
- result.hasQuotient = false;
- result.quotient_ = 0L;
- return this;
- }
-
- public bool HasRemainder {
- get { return result.hasRemainder; }
- }
- public long Remainder {
- get { return result.Remainder; }
- set { SetRemainder(value); }
- }
- public Builder SetRemainder(long value) {
- PrepareBuilder();
- result.hasRemainder = true;
- result.remainder_ = value;
- return this;
}
- public Builder ClearRemainder() {
- PrepareBuilder();
- result.hasRemainder = false;
- result.remainder_ = 0L;
- return this;
- }
- }
- static DivReply() {
- object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class FibArgs : pb::GeneratedMessage<FibArgs, FibArgs.Builder> {
- private FibArgs() { }
- private static readonly FibArgs defaultInstance = new FibArgs().MakeReadOnly();
- private static readonly string[] _fibArgsFieldNames = new string[] { "limit" };
- private static readonly uint[] _fibArgsFieldTags = new uint[] { 8 };
- public static FibArgs DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class FibArgs : pb::IMessage<FibArgs> {
+ private static readonly pb::MessageParser<FibArgs> _parser = new pb::MessageParser<FibArgs>(() => new FibArgs());
+ public static pb::MessageParser<FibArgs> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Math.Proto.Math.Descriptor.MessageTypes[2]; }
}
- public override FibArgs DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override FibArgs ThisMessage {
- get { return this; }
+ public FibArgs() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::math.Proto.Math.internal__static_math_FibArgs__Descriptor; }
+ partial void OnConstruction();
+
+ public FibArgs(FibArgs other) : this() {
+ limit_ = other.limit_;
}
- protected override pb::FieldAccess.FieldAccessorTable<FibArgs, FibArgs.Builder> InternalFieldAccessors {
- get { return global::math.Proto.Math.internal__static_math_FibArgs__FieldAccessorTable; }
+ public FibArgs Clone() {
+ return new FibArgs(this);
}
public const int LimitFieldNumber = 1;
- private bool hasLimit;
private long limit_;
- public bool HasLimit {
- get { return hasLimit; }
- }
public long Limit {
get { return limit_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ limit_ = value;
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _fibArgsFieldNames;
- if (hasLimit) {
- output.WriteInt64(1, field_names[0], Limit);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as FibArgs);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasLimit) {
- size += pb::CodedOutputStream.ComputeInt64Size(1, Limit);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(FibArgs other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Limit != other.Limit) return false;
+ return true;
}
- public static FibArgs ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static FibArgs ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static FibArgs ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static FibArgs ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static FibArgs ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static FibArgs ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static FibArgs ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static FibArgs ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static FibArgs ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static FibArgs ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private FibArgs MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Limit != 0L) hash ^= Limit.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(FibArgs prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<FibArgs, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(FibArgs cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private FibArgs result;
-
- private FibArgs PrepareBuilder() {
- if (resultIsReadOnly) {
- FibArgs original = result;
- result = new FibArgs();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override FibArgs MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::math.FibArgs.Descriptor; }
- }
-
- public override FibArgs DefaultInstanceForType {
- get { return global::math.FibArgs.DefaultInstance; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Limit != 0L) {
+ output.WriteRawTag(8);
+ output.WriteInt64(Limit);
}
+ }
- public override FibArgs BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
- }
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is FibArgs) {
- return MergeFrom((FibArgs) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ public int CalculateSize() {
+ int size = 0;
+ if (Limit != 0L) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(Limit);
}
+ return size;
+ }
- public override Builder MergeFrom(FibArgs other) {
- if (other == global::math.FibArgs.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasLimit) {
- Limit = other.Limit;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
+ public void MergeFrom(FibArgs other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ if (other.Limit != 0L) {
+ Limit = other.Limit;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_fibArgsFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _fibArgsFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Limit = input.ReadInt64();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- result.hasLimit = input.ReadInt64(ref result.limit_);
- break;
- }
- }
- }
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
}
- return this;
- }
-
-
- public bool HasLimit {
- get { return result.hasLimit; }
- }
- public long Limit {
- get { return result.Limit; }
- set { SetLimit(value); }
- }
- public Builder SetLimit(long value) {
- PrepareBuilder();
- result.hasLimit = true;
- result.limit_ = value;
- return this;
}
- public Builder ClearLimit() {
- PrepareBuilder();
- result.hasLimit = false;
- result.limit_ = 0L;
- return this;
- }
- }
- static FibArgs() {
- object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Num : pb::GeneratedMessage<Num, Num.Builder> {
- private Num() { }
- private static readonly Num defaultInstance = new Num().MakeReadOnly();
- private static readonly string[] _numFieldNames = new string[] { "num" };
- private static readonly uint[] _numFieldTags = new uint[] { 8 };
- public static Num DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class Num : pb::IMessage<Num> {
+ private static readonly pb::MessageParser<Num> _parser = new pb::MessageParser<Num>(() => new Num());
+ public static pb::MessageParser<Num> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Math.Proto.Math.Descriptor.MessageTypes[3]; }
}
- public override Num DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override Num ThisMessage {
- get { return this; }
+ public Num() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::math.Proto.Math.internal__static_math_Num__Descriptor; }
+ partial void OnConstruction();
+
+ public Num(Num other) : this() {
+ num_ = other.num_;
}
- protected override pb::FieldAccess.FieldAccessorTable<Num, Num.Builder> InternalFieldAccessors {
- get { return global::math.Proto.Math.internal__static_math_Num__FieldAccessorTable; }
+ public Num Clone() {
+ return new Num(this);
}
public const int Num_FieldNumber = 1;
- private bool hasNum_;
private long num_;
- public bool HasNum_ {
- get { return hasNum_; }
- }
public long Num_ {
get { return num_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ num_ = value;
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _numFieldNames;
- if (hasNum_) {
- output.WriteInt64(1, field_names[0], Num_);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as Num);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasNum_) {
- size += pb::CodedOutputStream.ComputeInt64Size(1, Num_);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(Num other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Num_ != other.Num_) return false;
+ return true;
}
- public static Num ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static Num ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static Num ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static Num ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static Num ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static Num ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static Num ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static Num ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static Num ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static Num ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private Num MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Num_ != 0L) hash ^= Num_.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(Num prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<Num, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(Num cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private Num result;
-
- private Num PrepareBuilder() {
- if (resultIsReadOnly) {
- Num original = result;
- result = new Num();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override Num MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::math.Num.Descriptor; }
- }
-
- public override Num DefaultInstanceForType {
- get { return global::math.Num.DefaultInstance; }
- }
-
- public override Num BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Num_ != 0L) {
+ output.WriteRawTag(8);
+ output.WriteInt64(Num_);
}
+ }
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is Num) {
- return MergeFrom((Num) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ public int CalculateSize() {
+ int size = 0;
+ if (Num_ != 0L) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(Num_);
}
+ return size;
+ }
- public override Builder MergeFrom(Num other) {
- if (other == global::math.Num.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasNum_) {
- Num_ = other.Num_;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
+ public void MergeFrom(Num other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ if (other.Num_ != 0L) {
+ Num_ = other.Num_;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_numFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _numFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
- }
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- result.hasNum_ = input.ReadInt64(ref result.num_);
- break;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Num_ = input.ReadInt64();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasNum_ {
- get { return result.hasNum_; }
- }
- public long Num_ {
- get { return result.Num_; }
- set { SetNum_(value); }
- }
- public Builder SetNum_(long value) {
- PrepareBuilder();
- result.hasNum_ = true;
- result.num_ = value;
- return this;
- }
- public Builder ClearNum_() {
- PrepareBuilder();
- result.hasNum_ = false;
- result.num_ = 0L;
- return this;
}
}
- static Num() {
- object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
- }
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class FibReply : pb::GeneratedMessage<FibReply, FibReply.Builder> {
- private FibReply() { }
- private static readonly FibReply defaultInstance = new FibReply().MakeReadOnly();
- private static readonly string[] _fibReplyFieldNames = new string[] { "count" };
- private static readonly uint[] _fibReplyFieldTags = new uint[] { 8 };
- public static FibReply DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class FibReply : pb::IMessage<FibReply> {
+ private static readonly pb::MessageParser<FibReply> _parser = new pb::MessageParser<FibReply>(() => new FibReply());
+ public static pb::MessageParser<FibReply> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Math.Proto.Math.Descriptor.MessageTypes[4]; }
}
- public override FibReply DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override FibReply ThisMessage {
- get { return this; }
+ public FibReply() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::math.Proto.Math.internal__static_math_FibReply__Descriptor; }
+ partial void OnConstruction();
+
+ public FibReply(FibReply other) : this() {
+ count_ = other.count_;
}
- protected override pb::FieldAccess.FieldAccessorTable<FibReply, FibReply.Builder> InternalFieldAccessors {
- get { return global::math.Proto.Math.internal__static_math_FibReply__FieldAccessorTable; }
+ public FibReply Clone() {
+ return new FibReply(this);
}
public const int CountFieldNumber = 1;
- private bool hasCount;
private long count_;
- public bool HasCount {
- get { return hasCount; }
- }
public long Count {
get { return count_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ count_ = value;
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _fibReplyFieldNames;
- if (hasCount) {
- output.WriteInt64(1, field_names[0], Count);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as FibReply);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasCount) {
- size += pb::CodedOutputStream.ComputeInt64Size(1, Count);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(FibReply other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
}
+ if (Count != other.Count) return false;
+ return true;
}
- public static FibReply ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static FibReply ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static FibReply ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static FibReply ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static FibReply ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static FibReply ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static FibReply ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static FibReply ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static FibReply ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static FibReply ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private FibReply MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Count != 0L) hash ^= Count.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(FibReply prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<FibReply, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(FibReply cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private FibReply result;
-
- private FibReply PrepareBuilder() {
- if (resultIsReadOnly) {
- FibReply original = result;
- result = new FibReply();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override FibReply MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::math.FibReply.Descriptor; }
- }
-
- public override FibReply DefaultInstanceForType {
- get { return global::math.FibReply.DefaultInstance; }
- }
-
- public override FibReply BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Count != 0L) {
+ output.WriteRawTag(8);
+ output.WriteInt64(Count);
}
+ }
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is FibReply) {
- return MergeFrom((FibReply) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ public int CalculateSize() {
+ int size = 0;
+ if (Count != 0L) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(Count);
}
+ return size;
+ }
- public override Builder MergeFrom(FibReply other) {
- if (other == global::math.FibReply.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasCount) {
- Count = other.Count;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
+ public void MergeFrom(FibReply other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ if (other.Count != 0L) {
+ Count = other.Count;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_fibReplyFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _fibReplyFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
- }
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- result.hasCount = input.ReadInt64(ref result.count_);
- break;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Count = input.ReadInt64();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
}
-
-
- public bool HasCount {
- get { return result.hasCount; }
- }
- public long Count {
- get { return result.Count; }
- set { SetCount(value); }
- }
- public Builder SetCount(long value) {
- PrepareBuilder();
- result.hasCount = true;
- result.count_ = value;
- return this;
- }
- public Builder ClearCount() {
- PrepareBuilder();
- result.hasCount = false;
- result.count_ = 0L;
- return this;
- }
- }
- static FibReply() {
- object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
- }
- #endregion
+ }
- #region Services
- /*
- * Service generation is now disabled by default, use the following option to enable:
- * option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
- */
#endregion
}
diff --git a/src/csharp/Grpc.Examples/MathExamples.cs b/src/csharp/Grpc.Examples/MathExamples.cs
index dc1bf43995..8009ccbbfa 100644
--- a/src/csharp/Grpc.Examples/MathExamples.cs
+++ b/src/csharp/Grpc.Examples/MathExamples.cs
@@ -34,25 +34,25 @@ using System.Collections.Generic;
using System.Threading.Tasks;
using Grpc.Core.Utils;
-namespace math
+namespace Math
{
public static class MathExamples
{
public static void DivExample(Math.IMathClient client)
{
- DivReply result = client.Div(new DivArgs.Builder { Dividend = 10, Divisor = 3 }.Build());
+ DivReply result = client.Div(new DivArgs { Dividend = 10, Divisor = 3 });
Console.WriteLine("Div Result: " + result);
}
public static async Task DivAsyncExample(Math.IMathClient client)
{
- DivReply result = await client.DivAsync(new DivArgs.Builder { Dividend = 4, Divisor = 5 }.Build());
+ DivReply result = await client.DivAsync(new DivArgs { Dividend = 4, Divisor = 5 });
Console.WriteLine("DivAsync Result: " + result);
}
public static async Task FibExample(Math.IMathClient client)
{
- using (var call = client.Fib(new FibArgs.Builder { Limit = 5 }.Build()))
+ using (var call = client.Fib(new FibArgs { Limit = 5 }))
{
List<Num> result = await call.ResponseStream.ToListAsync();
Console.WriteLine("Fib Result: " + string.Join("|", result));
@@ -63,9 +63,9 @@ namespace math
{
var numbers = new List<Num>
{
- new Num.Builder { Num_ = 1 }.Build(),
- new Num.Builder { Num_ = 2 }.Build(),
- new Num.Builder { Num_ = 3 }.Build()
+ new Num { Num_ = 1 },
+ new Num { Num_ = 2 },
+ new Num { Num_ = 3 }
};
using (var call = client.Sum())
@@ -79,9 +79,9 @@ namespace math
{
var divArgsList = new List<DivArgs>
{
- new DivArgs.Builder { Dividend = 10, Divisor = 3 }.Build(),
- new DivArgs.Builder { Dividend = 100, Divisor = 21 }.Build(),
- new DivArgs.Builder { Dividend = 7, Divisor = 2 }.Build()
+ new DivArgs { Dividend = 10, Divisor = 3 },
+ new DivArgs { Dividend = 100, Divisor = 21 },
+ new DivArgs { Dividend = 7, Divisor = 2 }
};
using (var call = client.DivMany())
{
@@ -94,9 +94,9 @@ namespace math
{
var numbers = new List<Num>
{
- new Num.Builder { Num_ = 1 }.Build(),
- new Num.Builder { Num_ = 2 }.Build(),
- new Num.Builder { Num_ = 3 }.Build()
+ new Num { Num_ = 1 },
+ new Num { Num_ = 2 },
+ new Num { Num_ = 3 }
};
Num sum;
@@ -106,7 +106,7 @@ namespace math
sum = await sumCall.ResponseAsync;
}
- DivReply result = await client.DivAsync(new DivArgs.Builder { Dividend = sum.Num_, Divisor = numbers.Count }.Build());
+ DivReply result = await client.DivAsync(new DivArgs { Dividend = sum.Num_, Divisor = numbers.Count });
Console.WriteLine("Avg Result: " + result);
}
}
diff --git a/src/csharp/Grpc.Examples/MathGrpc.cs b/src/csharp/Grpc.Examples/MathGrpc.cs
index 4941ff35f7..175d110f76 100644
--- a/src/csharp/Grpc.Examples/MathGrpc.cs
+++ b/src/csharp/Grpc.Examples/MathGrpc.cs
@@ -7,66 +7,72 @@ using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
-namespace math {
+namespace Math {
public static class Math
{
static readonly string __ServiceName = "math.Math";
- static readonly Marshaller<global::math.DivArgs> __Marshaller_DivArgs = Marshallers.Create((arg) => arg.ToByteArray(), global::math.DivArgs.ParseFrom);
- static readonly Marshaller<global::math.DivReply> __Marshaller_DivReply = Marshallers.Create((arg) => arg.ToByteArray(), global::math.DivReply.ParseFrom);
- static readonly Marshaller<global::math.FibArgs> __Marshaller_FibArgs = Marshallers.Create((arg) => arg.ToByteArray(), global::math.FibArgs.ParseFrom);
- static readonly Marshaller<global::math.Num> __Marshaller_Num = Marshallers.Create((arg) => arg.ToByteArray(), global::math.Num.ParseFrom);
+ static readonly Marshaller<global::Math.DivArgs> __Marshaller_DivArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.DivArgs.Parser.ParseFrom);
+ static readonly Marshaller<global::Math.DivReply> __Marshaller_DivReply = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.DivReply.Parser.ParseFrom);
+ static readonly Marshaller<global::Math.FibArgs> __Marshaller_FibArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.FibArgs.Parser.ParseFrom);
+ static readonly Marshaller<global::Math.Num> __Marshaller_Num = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.Num.Parser.ParseFrom);
- static readonly Method<global::math.DivArgs, global::math.DivReply> __Method_Div = new Method<global::math.DivArgs, global::math.DivReply>(
+ static readonly Method<global::Math.DivArgs, global::Math.DivReply> __Method_Div = new Method<global::Math.DivArgs, global::Math.DivReply>(
MethodType.Unary,
__ServiceName,
"Div",
__Marshaller_DivArgs,
__Marshaller_DivReply);
- static readonly Method<global::math.DivArgs, global::math.DivReply> __Method_DivMany = new Method<global::math.DivArgs, global::math.DivReply>(
+ static readonly Method<global::Math.DivArgs, global::Math.DivReply> __Method_DivMany = new Method<global::Math.DivArgs, global::Math.DivReply>(
MethodType.DuplexStreaming,
__ServiceName,
"DivMany",
__Marshaller_DivArgs,
__Marshaller_DivReply);
- static readonly Method<global::math.FibArgs, global::math.Num> __Method_Fib = new Method<global::math.FibArgs, global::math.Num>(
+ static readonly Method<global::Math.FibArgs, global::Math.Num> __Method_Fib = new Method<global::Math.FibArgs, global::Math.Num>(
MethodType.ServerStreaming,
__ServiceName,
"Fib",
__Marshaller_FibArgs,
__Marshaller_Num);
- static readonly Method<global::math.Num, global::math.Num> __Method_Sum = new Method<global::math.Num, global::math.Num>(
+ static readonly Method<global::Math.Num, global::Math.Num> __Method_Sum = new Method<global::Math.Num, global::Math.Num>(
MethodType.ClientStreaming,
__ServiceName,
"Sum",
__Marshaller_Num,
__Marshaller_Num);
+ // service descriptor
+ public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
+ {
+ get { return global::Math.Proto.Math.Descriptor.Services[0]; }
+ }
+
// client interface
public interface IMathClient
{
- global::math.DivReply Div(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- global::math.DivReply Div(global::math.DivArgs request, CallOptions options);
- AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, CallOptions options);
- AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(CallOptions options);
- AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, CallOptions options);
- AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(CallOptions options);
+ global::Math.DivReply Div(global::Math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ global::Math.DivReply Div(global::Math.DivArgs request, CallOptions options);
+ AsyncUnaryCall<global::Math.DivReply> DivAsync(global::Math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncUnaryCall<global::Math.DivReply> DivAsync(global::Math.DivArgs request, CallOptions options);
+ AsyncDuplexStreamingCall<global::Math.DivArgs, global::Math.DivReply> DivMany(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncDuplexStreamingCall<global::Math.DivArgs, global::Math.DivReply> DivMany(CallOptions options);
+ AsyncServerStreamingCall<global::Math.Num> Fib(global::Math.FibArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncServerStreamingCall<global::Math.Num> Fib(global::Math.FibArgs request, CallOptions options);
+ AsyncClientStreamingCall<global::Math.Num, global::Math.Num> Sum(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncClientStreamingCall<global::Math.Num, global::Math.Num> Sum(CallOptions options);
}
// server-side interface
public interface IMath
{
- Task<global::math.DivReply> Div(global::math.DivArgs request, ServerCallContext context);
- Task DivMany(IAsyncStreamReader<global::math.DivArgs> requestStream, IServerStreamWriter<global::math.DivReply> responseStream, ServerCallContext context);
- Task Fib(global::math.FibArgs request, IServerStreamWriter<global::math.Num> responseStream, ServerCallContext context);
- Task<global::math.Num> Sum(IAsyncStreamReader<global::math.Num> requestStream, ServerCallContext context);
+ Task<global::Math.DivReply> Div(global::Math.DivArgs request, ServerCallContext context);
+ Task DivMany(IAsyncStreamReader<global::Math.DivArgs> requestStream, IServerStreamWriter<global::Math.DivReply> responseStream, ServerCallContext context);
+ Task Fib(global::Math.FibArgs request, IServerStreamWriter<global::Math.Num> responseStream, ServerCallContext context);
+ Task<global::Math.Num> Sum(IAsyncStreamReader<global::Math.Num> requestStream, ServerCallContext context);
}
// client stub
@@ -75,52 +81,52 @@ namespace math {
public MathClient(Channel channel) : base(channel)
{
}
- public global::math.DivReply Div(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public global::Math.DivReply Div(global::Math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Div, new CallOptions(headers, deadline, cancellationToken));
return Calls.BlockingUnaryCall(call, request);
}
- public global::math.DivReply Div(global::math.DivArgs request, CallOptions options)
+ public global::Math.DivReply Div(global::Math.DivArgs request, CallOptions options)
{
var call = CreateCall(__Method_Div, options);
return Calls.BlockingUnaryCall(call, request);
}
- public AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncUnaryCall<global::Math.DivReply> DivAsync(global::Math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Div, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncUnaryCall(call, request);
}
- public AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, CallOptions options)
+ public AsyncUnaryCall<global::Math.DivReply> DivAsync(global::Math.DivArgs request, CallOptions options)
{
var call = CreateCall(__Method_Div, options);
return Calls.AsyncUnaryCall(call, request);
}
- public AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncDuplexStreamingCall<global::Math.DivArgs, global::Math.DivReply> DivMany(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_DivMany, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncDuplexStreamingCall(call);
}
- public AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(CallOptions options)
+ public AsyncDuplexStreamingCall<global::Math.DivArgs, global::Math.DivReply> DivMany(CallOptions options)
{
var call = CreateCall(__Method_DivMany, options);
return Calls.AsyncDuplexStreamingCall(call);
}
- public AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncServerStreamingCall<global::Math.Num> Fib(global::Math.FibArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Fib, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncServerStreamingCall(call, request);
}
- public AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, CallOptions options)
+ public AsyncServerStreamingCall<global::Math.Num> Fib(global::Math.FibArgs request, CallOptions options)
{
var call = CreateCall(__Method_Fib, options);
return Calls.AsyncServerStreamingCall(call, request);
}
- public AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncClientStreamingCall<global::Math.Num, global::Math.Num> Sum(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Sum, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncClientStreamingCall(call);
}
- public AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(CallOptions options)
+ public AsyncClientStreamingCall<global::Math.Num, global::Math.Num> Sum(CallOptions options)
{
var call = CreateCall(__Method_Sum, options);
return Calls.AsyncClientStreamingCall(call);
diff --git a/src/csharp/Grpc.Examples/MathServiceImpl.cs b/src/csharp/Grpc.Examples/MathServiceImpl.cs
index 7b2684615c..71dc655e46 100644
--- a/src/csharp/Grpc.Examples/MathServiceImpl.cs
+++ b/src/csharp/Grpc.Examples/MathServiceImpl.cs
@@ -38,7 +38,7 @@ using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Utils;
-namespace math
+namespace Math
{
/// <summary>
/// Implementation of MathService server
@@ -79,7 +79,7 @@ namespace math
{
sum += num.Num_;
});
- return Num.CreateBuilder().SetNum_(sum).Build();
+ return new Num { Num_ = sum };
}
public async Task DivMany(IAsyncStreamReader<DivArgs> requestStream, IServerStreamWriter<DivReply> responseStream, ServerCallContext context)
@@ -91,13 +91,13 @@ namespace math
{
long quotient = args.Dividend / args.Divisor;
long remainder = args.Dividend % args.Divisor;
- return new DivReply.Builder { Quotient = quotient, Remainder = remainder }.Build();
+ return new DivReply { Quotient = quotient, Remainder = remainder };
}
static IEnumerable<Num> FibInternal(long n)
{
long a = 1;
- yield return new Num.Builder { Num_ = a }.Build();
+ yield return new Num { Num_ = a };
long b = 1;
for (long i = 0; i < n - 1; i++)
@@ -105,7 +105,7 @@ namespace math
long temp = a;
a = b;
b = temp + b;
- yield return new Num.Builder { Num_ = a }.Build();
+ yield return new Num { Num_ = a };
}
}
}
diff --git a/src/csharp/Grpc.Examples/packages.config b/src/csharp/Grpc.Examples/packages.config
index 4c8d60fa62..adf8da2363 100644
--- a/src/csharp/Grpc.Examples/packages.config
+++ b/src/csharp/Grpc.Examples/packages.config
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
- <package id="Google.ProtocolBuffers" version="2.4.1.521" targetFramework="net45" />
+ <package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
<package id="NUnit" version="2.6.4" targetFramework="net45" />
</packages> \ No newline at end of file
diff --git a/src/csharp/Grpc.Examples/proto/math.proto b/src/csharp/Grpc.Examples/proto/math.proto
index 5485d580c3..311e148c02 100644
--- a/src/csharp/Grpc.Examples/proto/math.proto
+++ b/src/csharp/Grpc.Examples/proto/math.proto
@@ -28,30 +28,30 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-syntax = "proto2";
+syntax = "proto3";
package math;
message DivArgs {
- optional int64 dividend = 1;
- optional int64 divisor = 2;
+ int64 dividend = 1;
+ int64 divisor = 2;
}
message DivReply {
- optional int64 quotient = 1;
- optional int64 remainder = 2;
+ int64 quotient = 1;
+ int64 remainder = 2;
}
message FibArgs {
- optional int64 limit = 1;
+ int64 limit = 1;
}
message Num {
- optional int64 num = 1;
+ int64 num = 1;
}
message FibReply {
- optional int64 count = 1;
+ int64 count = 1;
}
service Math {
diff --git a/src/csharp/Grpc.HealthCheck.Tests/Grpc.HealthCheck.Tests.csproj b/src/csharp/Grpc.HealthCheck.Tests/Grpc.HealthCheck.Tests.csproj
index c922ddfb9e..396dc43a02 100644
--- a/src/csharp/Grpc.HealthCheck.Tests/Grpc.HealthCheck.Tests.csproj
+++ b/src/csharp/Grpc.HealthCheck.Tests/Grpc.HealthCheck.Tests.csproj
@@ -37,11 +37,9 @@
<AssemblyOriginatorKeyFile>C:\keys\Grpc.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
- <Reference Include="Google.ProtocolBuffers">
- <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll</HintPath>
- </Reference>
- <Reference Include="Google.ProtocolBuffers.Serialization">
- <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll</HintPath>
+ <Reference Include="Google.Protobuf, Version=3.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<HintPath>..\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath>
diff --git a/src/csharp/Grpc.HealthCheck.Tests/HealthClientServerTest.cs b/src/csharp/Grpc.HealthCheck.Tests/HealthClientServerTest.cs
index 80c35fb197..6c3a53bec0 100644
--- a/src/csharp/Grpc.HealthCheck.Tests/HealthClientServerTest.cs
+++ b/src/csharp/Grpc.HealthCheck.Tests/HealthClientServerTest.cs
@@ -81,14 +81,14 @@ namespace Grpc.HealthCheck.Tests
{
serviceImpl.SetStatus("", "", HealthCheckResponse.Types.ServingStatus.SERVING);
- var response = client.Check(HealthCheckRequest.CreateBuilder().SetHost("").SetService("").Build());
+ var response = client.Check(new HealthCheckRequest { Host = "", Service = "" });
Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.SERVING, response.Status);
}
[Test]
public void ServiceDoesntExist()
{
- Assert.Throws(Is.TypeOf(typeof(RpcException)).And.Property("Status").Property("StatusCode").EqualTo(StatusCode.NotFound), () => client.Check(HealthCheckRequest.CreateBuilder().SetHost("").SetService("nonexistent.service").Build()));
+ Assert.Throws(Is.TypeOf(typeof(RpcException)).And.Property("Status").Property("StatusCode").EqualTo(StatusCode.NotFound), () => client.Check(new HealthCheckRequest { Host = "", Service = "nonexistent.service" }));
}
// TODO(jtattermusch): add test with timeout once timeouts are supported
diff --git a/src/csharp/Grpc.HealthCheck.Tests/HealthServiceImplTest.cs b/src/csharp/Grpc.HealthCheck.Tests/HealthServiceImplTest.cs
index c4caa3b57a..2097c0dc8c 100644
--- a/src/csharp/Grpc.HealthCheck.Tests/HealthServiceImplTest.cs
+++ b/src/csharp/Grpc.HealthCheck.Tests/HealthServiceImplTest.cs
@@ -101,7 +101,7 @@ namespace Grpc.HealthCheck.Tests
private static HealthCheckResponse.Types.ServingStatus GetStatusHelper(HealthServiceImpl impl, string host, string service)
{
- return impl.Check(HealthCheckRequest.CreateBuilder().SetHost(host).SetService(service).Build(), null).Result.Status;
+ return impl.Check(new HealthCheckRequest { Host = host, Service = service }, null).Result.Status;
}
}
}
diff --git a/src/csharp/Grpc.HealthCheck.Tests/packages.config b/src/csharp/Grpc.HealthCheck.Tests/packages.config
index 050c4eaed6..40ffb85203 100644
--- a/src/csharp/Grpc.HealthCheck.Tests/packages.config
+++ b/src/csharp/Grpc.HealthCheck.Tests/packages.config
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
- <package id="Google.ProtocolBuffers" version="2.4.1.555" targetFramework="net45" />
+ <package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="NUnit" version="2.6.4" targetFramework="net45" />
</packages> \ No newline at end of file
diff --git a/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.csproj b/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.csproj
index 0b7a7b91c6..8fce5d39aa 100644
--- a/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.csproj
+++ b/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.csproj
@@ -38,11 +38,9 @@
<AssemblyOriginatorKeyFile>C:\keys\Grpc.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
- <Reference Include="Google.ProtocolBuffers">
- <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll</HintPath>
- </Reference>
- <Reference Include="Google.ProtocolBuffers.Serialization">
- <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll</HintPath>
+ <Reference Include="Google.Protobuf, Version=3.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
diff --git a/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.nuspec b/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.nuspec
index acdfba42c8..66386288df 100644
--- a/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.nuspec
+++ b/src/csharp/Grpc.HealthCheck/Grpc.HealthCheck.nuspec
@@ -14,7 +14,7 @@
<copyright>Copyright 2015, Google Inc.</copyright>
<tags>gRPC health check</tags>
<dependencies>
- <dependency id="Google.ProtocolBuffers" version="2.4.1.555" />
+ <dependency id="Google.Protobuf" version="$ProtobufVersion$" />
<dependency id="Grpc.Core" version="$version$" />
<dependency id="Ix-Async" version="1.2.3" />
</dependencies>
diff --git a/src/csharp/Grpc.HealthCheck/Health.cs b/src/csharp/Grpc.HealthCheck/Health.cs
index 361382d4bd..570e274544 100644
--- a/src/csharp/Grpc.HealthCheck/Health.cs
+++ b/src/csharp/Grpc.HealthCheck/Health.cs
@@ -3,9 +3,9 @@
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
-using pb = global::Google.ProtocolBuffers;
-using pbc = global::Google.ProtocolBuffers.Collections;
-using pbd = global::Google.ProtocolBuffers.Descriptors;
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Health.V1Alpha {
@@ -14,21 +14,11 @@ namespace Grpc.Health.V1Alpha {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Health {
- #region Extension registration
- public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
- }
- #endregion
- #region Static variables
- internal static pbd::MessageDescriptor internal__static_grpc_health_v1alpha_HealthCheckRequest__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::Grpc.Health.V1Alpha.HealthCheckRequest, global::Grpc.Health.V1Alpha.HealthCheckRequest.Builder> internal__static_grpc_health_v1alpha_HealthCheckRequest__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_health_v1alpha_HealthCheckResponse__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::Grpc.Health.V1Alpha.HealthCheckResponse, global::Grpc.Health.V1Alpha.HealthCheckResponse.Builder> internal__static_grpc_health_v1alpha_HealthCheckResponse__FieldAccessorTable;
- #endregion
#region Descriptor
- public static pbd::FileDescriptor Descriptor {
+ public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
- private static pbd::FileDescriptor descriptor;
+ private static pbr::FileDescriptor descriptor;
static Health() {
byte[] descriptorData = global::System.Convert.FromBase64String(
@@ -41,24 +31,13 @@ namespace Grpc.Health.V1Alpha {
"EAESDwoLTk9UX1NFUlZJTkcQAjJkCgZIZWFsdGgSWgoFQ2hlY2sSJy5ncnBj",
"LmhlYWx0aC52MWFscGhhLkhlYWx0aENoZWNrUmVxdWVzdBooLmdycGMuaGVh",
"bHRoLnYxYWxwaGEuSGVhbHRoQ2hlY2tSZXNwb25zZUIWqgITR3JwYy5IZWFs",
- "dGguVjFBbHBoYQ=="));
- pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
- descriptor = root;
- internal__static_grpc_health_v1alpha_HealthCheckRequest__Descriptor = Descriptor.MessageTypes[0];
- internal__static_grpc_health_v1alpha_HealthCheckRequest__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::Grpc.Health.V1Alpha.HealthCheckRequest, global::Grpc.Health.V1Alpha.HealthCheckRequest.Builder>(internal__static_grpc_health_v1alpha_HealthCheckRequest__Descriptor,
- new string[] { "Host", "Service", });
- internal__static_grpc_health_v1alpha_HealthCheckResponse__Descriptor = Descriptor.MessageTypes[1];
- internal__static_grpc_health_v1alpha_HealthCheckResponse__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::Grpc.Health.V1Alpha.HealthCheckResponse, global::Grpc.Health.V1Alpha.HealthCheckResponse.Builder>(internal__static_grpc_health_v1alpha_HealthCheckResponse__Descriptor,
- new string[] { "Status", });
- pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
- RegisterAllExtensions(registry);
- return registry;
- };
- pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
- new pbd::FileDescriptor[] {
- }, assigner);
+ "dGguVjFBbHBoYWIGcHJvdG8z"));
+ descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
+ new pbr::FileDescriptor[] { },
+ new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Health.V1Alpha.HealthCheckRequest), new[]{ "Host", "Service" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Health.V1Alpha.HealthCheckResponse), new[]{ "Status" }, null, new[]{ typeof(global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus) }, null)
+ }));
}
#endregion
@@ -66,618 +45,245 @@ namespace Grpc.Health.V1Alpha {
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class HealthCheckRequest : pb::GeneratedMessage<HealthCheckRequest, HealthCheckRequest.Builder> {
- private HealthCheckRequest() { }
- private static readonly HealthCheckRequest defaultInstance = new HealthCheckRequest().MakeReadOnly();
- private static readonly string[] _healthCheckRequestFieldNames = new string[] { "host", "service" };
- private static readonly uint[] _healthCheckRequestFieldTags = new uint[] { 10, 18 };
- public static HealthCheckRequest DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class HealthCheckRequest : pb::IMessage<HealthCheckRequest> {
+ private static readonly pb::MessageParser<HealthCheckRequest> _parser = new pb::MessageParser<HealthCheckRequest>(() => new HealthCheckRequest());
+ public static pb::MessageParser<HealthCheckRequest> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Health.V1Alpha.Proto.Health.Descriptor.MessageTypes[0]; }
}
- public override HealthCheckRequest DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override HealthCheckRequest ThisMessage {
- get { return this; }
+ public HealthCheckRequest() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::Grpc.Health.V1Alpha.Proto.Health.internal__static_grpc_health_v1alpha_HealthCheckRequest__Descriptor; }
+ partial void OnConstruction();
+
+ public HealthCheckRequest(HealthCheckRequest other) : this() {
+ host_ = other.host_;
+ service_ = other.service_;
}
- protected override pb::FieldAccess.FieldAccessorTable<HealthCheckRequest, HealthCheckRequest.Builder> InternalFieldAccessors {
- get { return global::Grpc.Health.V1Alpha.Proto.Health.internal__static_grpc_health_v1alpha_HealthCheckRequest__FieldAccessorTable; }
+ public HealthCheckRequest Clone() {
+ return new HealthCheckRequest(this);
}
public const int HostFieldNumber = 1;
- private bool hasHost;
private string host_ = "";
- public bool HasHost {
- get { return hasHost; }
- }
public string Host {
get { return host_; }
+ set {
+ host_ = pb::Preconditions.CheckNotNull(value, "value");
+ }
}
public const int ServiceFieldNumber = 2;
- private bool hasService;
private string service_ = "";
- public bool HasService {
- get { return hasService; }
- }
public string Service {
get { return service_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
- }
- }
-
- public override void WriteTo(pb::ICodedOutputStream output) {
- CalcSerializedSize();
- string[] field_names = _healthCheckRequestFieldNames;
- if (hasHost) {
- output.WriteString(1, field_names[0], Host);
- }
- if (hasService) {
- output.WriteString(2, field_names[1], Service);
+ set {
+ service_ = pb::Preconditions.CheckNotNull(value, "value");
}
- UnknownFields.WriteTo(output);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
- return CalcSerializedSize();
- }
+ public override bool Equals(object other) {
+ return Equals(other as HealthCheckRequest);
}
- private int CalcSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasHost) {
- size += pb::CodedOutputStream.ComputeStringSize(1, Host);
+ public bool Equals(HealthCheckRequest other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
- if (hasService) {
- size += pb::CodedOutputStream.ComputeStringSize(2, Service);
+ if (ReferenceEquals(other, this)) {
+ return true;
}
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
- }
- public static HealthCheckRequest ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static HealthCheckRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static HealthCheckRequest ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static HealthCheckRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static HealthCheckRequest ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static HealthCheckRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static HealthCheckRequest ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static HealthCheckRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static HealthCheckRequest ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static HealthCheckRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private HealthCheckRequest MakeReadOnly() {
- return this;
+ if (Host != other.Host) return false;
+ if (Service != other.Service) return false;
+ return true;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(HealthCheckRequest prototype) {
- return new Builder(prototype);
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Host.Length != 0) hash ^= Host.GetHashCode();
+ if (Service.Length != 0) hash ^= Service.GetHashCode();
+ return hash;
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<HealthCheckRequest, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(HealthCheckRequest cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private HealthCheckRequest result;
-
- private HealthCheckRequest PrepareBuilder() {
- if (resultIsReadOnly) {
- HealthCheckRequest original = result;
- result = new HealthCheckRequest();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override HealthCheckRequest MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
+ }
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Host.Length != 0) {
+ output.WriteRawTag(10);
+ output.WriteString(Host);
}
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::Grpc.Health.V1Alpha.HealthCheckRequest.Descriptor; }
+ if (Service.Length != 0) {
+ output.WriteRawTag(18);
+ output.WriteString(Service);
}
+ }
- public override HealthCheckRequest DefaultInstanceForType {
- get { return global::Grpc.Health.V1Alpha.HealthCheckRequest.DefaultInstance; }
+ public int CalculateSize() {
+ int size = 0;
+ if (Host.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(Host);
}
-
- public override HealthCheckRequest BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ if (Service.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(Service);
}
+ return size;
+ }
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is HealthCheckRequest) {
- return MergeFrom((HealthCheckRequest) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ public void MergeFrom(HealthCheckRequest other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(HealthCheckRequest other) {
- if (other == global::Grpc.Health.V1Alpha.HealthCheckRequest.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasHost) {
- Host = other.Host;
- }
- if (other.HasService) {
- Service = other.Service;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
+ if (other.Host.Length != 0) {
+ Host = other.Host;
}
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ if (other.Service.Length != 0) {
+ Service = other.Service;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_healthCheckRequestFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _healthCheckRequestFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 10: {
+ Host = input.ReadString();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 10: {
- result.hasHost = input.ReadString(ref result.host_);
- break;
- }
- case 18: {
- result.hasService = input.ReadString(ref result.service_);
- break;
- }
+ case 18: {
+ Service = input.ReadString();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasHost {
- get { return result.hasHost; }
- }
- public string Host {
- get { return result.Host; }
- set { SetHost(value); }
- }
- public Builder SetHost(string value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasHost = true;
- result.host_ = value;
- return this;
- }
- public Builder ClearHost() {
- PrepareBuilder();
- result.hasHost = false;
- result.host_ = "";
- return this;
- }
-
- public bool HasService {
- get { return result.hasService; }
- }
- public string Service {
- get { return result.Service; }
- set { SetService(value); }
}
- public Builder SetService(string value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasService = true;
- result.service_ = value;
- return this;
- }
- public Builder ClearService() {
- PrepareBuilder();
- result.hasService = false;
- result.service_ = "";
- return this;
- }
- }
- static HealthCheckRequest() {
- object.ReferenceEquals(global::Grpc.Health.V1Alpha.Proto.Health.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class HealthCheckResponse : pb::GeneratedMessage<HealthCheckResponse, HealthCheckResponse.Builder> {
- private HealthCheckResponse() { }
- private static readonly HealthCheckResponse defaultInstance = new HealthCheckResponse().MakeReadOnly();
- private static readonly string[] _healthCheckResponseFieldNames = new string[] { "status" };
- private static readonly uint[] _healthCheckResponseFieldTags = new uint[] { 8 };
- public static HealthCheckResponse DefaultInstance {
- get { return defaultInstance; }
- }
+ public sealed partial class HealthCheckResponse : pb::IMessage<HealthCheckResponse> {
+ private static readonly pb::MessageParser<HealthCheckResponse> _parser = new pb::MessageParser<HealthCheckResponse>(() => new HealthCheckResponse());
+ public static pb::MessageParser<HealthCheckResponse> Parser { get { return _parser; } }
- public override HealthCheckResponse DefaultInstanceForType {
- get { return DefaultInstance; }
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Health.V1Alpha.Proto.Health.Descriptor.MessageTypes[1]; }
}
- protected override HealthCheckResponse ThisMessage {
- get { return this; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::Grpc.Health.V1Alpha.Proto.Health.internal__static_grpc_health_v1alpha_HealthCheckResponse__Descriptor; }
+ public HealthCheckResponse() {
+ OnConstruction();
}
- protected override pb::FieldAccess.FieldAccessorTable<HealthCheckResponse, HealthCheckResponse.Builder> InternalFieldAccessors {
- get { return global::Grpc.Health.V1Alpha.Proto.Health.internal__static_grpc_health_v1alpha_HealthCheckResponse__FieldAccessorTable; }
- }
+ partial void OnConstruction();
- #region Nested types
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public static partial class Types {
- public enum ServingStatus {
- UNKNOWN = 0,
- SERVING = 1,
- NOT_SERVING = 2,
- }
+ public HealthCheckResponse(HealthCheckResponse other) : this() {
+ status_ = other.status_;
+ }
+ public HealthCheckResponse Clone() {
+ return new HealthCheckResponse(this);
}
- #endregion
public const int StatusFieldNumber = 1;
- private bool hasStatus;
private global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus status_ = global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN;
- public bool HasStatus {
- get { return hasStatus; }
- }
public global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus Status {
get { return status_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ status_ = value;
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- CalcSerializedSize();
- string[] field_names = _healthCheckResponseFieldNames;
- if (hasStatus) {
- output.WriteEnum(1, field_names[0], (int) Status, Status);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as HealthCheckResponse);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
- return CalcSerializedSize();
+ public bool Equals(HealthCheckResponse other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
- }
-
- private int CalcSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasStatus) {
- size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Status);
+ if (ReferenceEquals(other, this)) {
+ return true;
}
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
- }
- public static HealthCheckResponse ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static HealthCheckResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static HealthCheckResponse ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static HealthCheckResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static HealthCheckResponse ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static HealthCheckResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static HealthCheckResponse ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static HealthCheckResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static HealthCheckResponse ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static HealthCheckResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private HealthCheckResponse MakeReadOnly() {
- return this;
+ if (Status != other.Status) return false;
+ return true;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(HealthCheckResponse prototype) {
- return new Builder(prototype);
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) hash ^= Status.GetHashCode();
+ return hash;
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<HealthCheckResponse, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(HealthCheckResponse cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private HealthCheckResponse result;
-
- private HealthCheckResponse PrepareBuilder() {
- if (resultIsReadOnly) {
- HealthCheckResponse original = result;
- result = new HealthCheckResponse();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override HealthCheckResponse MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::Grpc.Health.V1Alpha.HealthCheckResponse.Descriptor; }
- }
-
- public override HealthCheckResponse DefaultInstanceForType {
- get { return global::Grpc.Health.V1Alpha.HealthCheckResponse.DefaultInstance; }
- }
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
+ }
- public override HealthCheckResponse BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) {
+ output.WriteRawTag(8);
+ output.WriteEnum((int) Status);
}
+ }
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is HealthCheckResponse) {
- return MergeFrom((HealthCheckResponse) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ public int CalculateSize() {
+ int size = 0;
+ if (Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) {
+ size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status);
}
+ return size;
+ }
- public override Builder MergeFrom(HealthCheckResponse other) {
- if (other == global::Grpc.Health.V1Alpha.HealthCheckResponse.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasStatus) {
- Status = other.Status;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
+ public void MergeFrom(HealthCheckResponse other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ if (other.Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) {
+ Status = other.Status;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_healthCheckResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _healthCheckResponseFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ status_ = (global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus) input.ReadEnum();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- object unknown;
- if(input.ReadEnum(ref result.status_, out unknown)) {
- result.hasStatus = true;
- } else if(unknown is int) {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- unknownFields.MergeVarintField(1, (ulong)(int)unknown);
- }
- break;
- }
- }
- }
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
}
- return this;
}
+ }
-
- public bool HasStatus {
- get { return result.hasStatus; }
- }
- public global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus Status {
- get { return result.Status; }
- set { SetStatus(value); }
- }
- public Builder SetStatus(global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus value) {
- PrepareBuilder();
- result.hasStatus = true;
- result.status_ = value;
- return this;
- }
- public Builder ClearStatus() {
- PrepareBuilder();
- result.hasStatus = false;
- result.status_ = global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN;
- return this;
+ #region Nested types
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ public static partial class Types {
+ public enum ServingStatus {
+ UNKNOWN = 0,
+ SERVING = 1,
+ NOT_SERVING = 2,
}
+
}
- static HealthCheckResponse() {
- object.ReferenceEquals(global::Grpc.Health.V1Alpha.Proto.Health.Descriptor, null);
- }
+ #endregion
+
}
#endregion
diff --git a/src/csharp/Grpc.HealthCheck/HealthGrpc.cs b/src/csharp/Grpc.HealthCheck/HealthGrpc.cs
index 0dabc91f7c..da721ce5f6 100644
--- a/src/csharp/Grpc.HealthCheck/HealthGrpc.cs
+++ b/src/csharp/Grpc.HealthCheck/HealthGrpc.cs
@@ -12,8 +12,8 @@ namespace Grpc.Health.V1Alpha {
{
static readonly string __ServiceName = "grpc.health.v1alpha.Health";
- static readonly Marshaller<global::Grpc.Health.V1Alpha.HealthCheckRequest> __Marshaller_HealthCheckRequest = Marshallers.Create((arg) => arg.ToByteArray(), global::Grpc.Health.V1Alpha.HealthCheckRequest.ParseFrom);
- static readonly Marshaller<global::Grpc.Health.V1Alpha.HealthCheckResponse> __Marshaller_HealthCheckResponse = Marshallers.Create((arg) => arg.ToByteArray(), global::Grpc.Health.V1Alpha.HealthCheckResponse.ParseFrom);
+ static readonly Marshaller<global::Grpc.Health.V1Alpha.HealthCheckRequest> __Marshaller_HealthCheckRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Health.V1Alpha.HealthCheckRequest.Parser.ParseFrom);
+ static readonly Marshaller<global::Grpc.Health.V1Alpha.HealthCheckResponse> __Marshaller_HealthCheckResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Health.V1Alpha.HealthCheckResponse.Parser.ParseFrom);
static readonly Method<global::Grpc.Health.V1Alpha.HealthCheckRequest, global::Grpc.Health.V1Alpha.HealthCheckResponse> __Method_Check = new Method<global::Grpc.Health.V1Alpha.HealthCheckRequest, global::Grpc.Health.V1Alpha.HealthCheckResponse>(
MethodType.Unary,
@@ -22,6 +22,12 @@ namespace Grpc.Health.V1Alpha {
__Marshaller_HealthCheckRequest,
__Marshaller_HealthCheckResponse);
+ // service descriptor
+ public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
+ {
+ get { return global::Grpc.Health.V1Alpha.Proto.Health.Descriptor.Services[0]; }
+ }
+
// client interface
public interface IHealthClient
{
diff --git a/src/csharp/Grpc.HealthCheck/HealthServiceImpl.cs b/src/csharp/Grpc.HealthCheck/HealthServiceImpl.cs
index 8c04b43a86..26c6445c35 100644
--- a/src/csharp/Grpc.HealthCheck/HealthServiceImpl.cs
+++ b/src/csharp/Grpc.HealthCheck/HealthServiceImpl.cs
@@ -105,8 +105,8 @@ namespace Grpc.HealthCheck
{
lock (myLock)
{
- var host = request.HasHost ? request.Host : "";
- var service = request.HasService ? request.Service : "";
+ var host = request.Host;
+ var service = request.Service;
HealthCheckResponse.Types.ServingStatus status;
if (!statusMap.TryGetValue(CreateKey(host, service), out status))
@@ -114,7 +114,7 @@ namespace Grpc.HealthCheck
// TODO(jtattermusch): returning specific status from server handler is not supported yet.
throw new RpcException(new Status(StatusCode.NotFound, ""));
}
- return Task.FromResult(HealthCheckResponse.CreateBuilder().SetStatus(status).Build());
+ return Task.FromResult(new HealthCheckResponse { Status = status });
}
}
diff --git a/src/csharp/Grpc.HealthCheck/packages.config b/src/csharp/Grpc.HealthCheck/packages.config
index 094a30981e..cafff6123a 100644
--- a/src/csharp/Grpc.HealthCheck/packages.config
+++ b/src/csharp/Grpc.HealthCheck/packages.config
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
- <package id="Google.ProtocolBuffers" version="2.4.1.555" targetFramework="net45" />
+ <package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
</packages> \ No newline at end of file
diff --git a/src/csharp/Grpc.HealthCheck/proto/health.proto b/src/csharp/Grpc.HealthCheck/proto/health.proto
index 08df7e104e..01aa3fcf57 100644
--- a/src/csharp/Grpc.HealthCheck/proto/health.proto
+++ b/src/csharp/Grpc.HealthCheck/proto/health.proto
@@ -28,14 +28,14 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// TODO(jtattermusch): switch to proto3 once C# supports that.
-syntax = "proto2";
+syntax = "proto3";
package grpc.health.v1alpha;
option csharp_namespace = "Grpc.Health.V1Alpha";
message HealthCheckRequest {
- optional string host = 1;
- optional string service = 2;
+ string host = 1;
+ string service = 2;
}
message HealthCheckResponse {
@@ -44,7 +44,7 @@ message HealthCheckResponse {
SERVING = 1;
NOT_SERVING = 2;
}
- optional ServingStatus status = 1;
+ ServingStatus status = 1;
}
service Health {
diff --git a/src/csharp/Grpc.IntegrationTesting/Empty.cs b/src/csharp/Grpc.IntegrationTesting/Empty.cs
index 7169ee2a4a..28c28c9afd 100644
--- a/src/csharp/Grpc.IntegrationTesting/Empty.cs
+++ b/src/csharp/Grpc.IntegrationTesting/Empty.cs
@@ -1,47 +1,34 @@
-// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: empty.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
-using pb = global::Google.ProtocolBuffers;
-using pbc = global::Google.ProtocolBuffers.Collections;
-using pbd = global::Google.ProtocolBuffers.Descriptors;
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
-namespace grpc.testing {
+namespace Grpc.Testing {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Empty {
- #region Extension registration
- public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
- }
- #endregion
- #region Static variables
- internal static pbd::MessageDescriptor internal__static_grpc_testing_Empty__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.Empty, global::grpc.testing.Empty.Builder> internal__static_grpc_testing_Empty__FieldAccessorTable;
- #endregion
#region Descriptor
- public static pbd::FileDescriptor Descriptor {
+ public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
- private static pbd::FileDescriptor descriptor;
+ private static pbr::FileDescriptor descriptor;
static Empty() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "CgtlbXB0eS5wcm90bxIMZ3JwYy50ZXN0aW5nIgcKBUVtcHR5"));
- pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
- descriptor = root;
- internal__static_grpc_testing_Empty__Descriptor = Descriptor.MessageTypes[0];
- internal__static_grpc_testing_Empty__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.Empty, global::grpc.testing.Empty.Builder>(internal__static_grpc_testing_Empty__Descriptor,
- new string[] { });
- return null;
- };
- pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
- new pbd::FileDescriptor[] {
- }, assigner);
+ "CgtlbXB0eS5wcm90bxIMZ3JwYy50ZXN0aW5nIgcKBUVtcHR5YgZwcm90bzM="));
+ descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
+ new pbr::FileDescriptor[] { },
+ new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.Empty), null, null, null, null)
+ }));
}
#endregion
@@ -49,230 +36,79 @@ namespace grpc.testing {
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Empty : pb::GeneratedMessage<Empty, Empty.Builder> {
- private Empty() { }
- private static readonly Empty defaultInstance = new Empty().MakeReadOnly();
- private static readonly string[] _emptyFieldNames = new string[] { };
- private static readonly uint[] _emptyFieldTags = new uint[] { };
- public static Empty DefaultInstance {
- get { return defaultInstance; }
- }
+ public sealed partial class Empty : pb::IMessage<Empty> {
+ private static readonly pb::MessageParser<Empty> _parser = new pb::MessageParser<Empty>(() => new Empty());
+ public static pb::MessageParser<Empty> Parser { get { return _parser; } }
- public override Empty DefaultInstanceForType {
- get { return DefaultInstance; }
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Proto.Empty.Descriptor.MessageTypes[0]; }
}
- protected override Empty ThisMessage {
- get { return this; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Proto.Empty.internal__static_grpc_testing_Empty__Descriptor; }
+ public Empty() {
+ OnConstruction();
}
- protected override pb::FieldAccess.FieldAccessorTable<Empty, Empty.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Proto.Empty.internal__static_grpc_testing_Empty__FieldAccessorTable; }
- }
+ partial void OnConstruction();
- public override bool IsInitialized {
- get {
- return true;
- }
+ public Empty(Empty other) : this() {
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _emptyFieldNames;
- UnknownFields.WriteTo(output);
+ public Empty Clone() {
+ return new Empty(this);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
+ public override bool Equals(object other) {
+ return Equals(other as Empty);
+ }
- size = 0;
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(Empty other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
}
+ return true;
}
- public static Empty ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static Empty ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static Empty ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static Empty ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static Empty ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static Empty ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static Empty ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static Empty ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static Empty ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static Empty ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private Empty MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(Empty prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<Empty, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(Empty cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private Empty result;
-
- private Empty PrepareBuilder() {
- if (resultIsReadOnly) {
- Empty original = result;
- result = new Empty();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override Empty MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.Empty.Descriptor; }
- }
-
- public override Empty DefaultInstanceForType {
- get { return global::grpc.testing.Empty.DefaultInstance; }
- }
-
- public override Empty BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
- }
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is Empty) {
- return MergeFrom((Empty) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
- }
+ public void WriteTo(pb::CodedOutputStream output) {
+ }
- public override Builder MergeFrom(Empty other) {
- if (other == global::grpc.testing.Empty.DefaultInstance) return this;
- PrepareBuilder();
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
+ public int CalculateSize() {
+ int size = 0;
+ return size;
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
+ public void MergeFrom(Empty other) {
+ if (other == null) {
+ return;
}
+ }
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_emptyFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _emptyFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
- }
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- }
- }
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
}
- return this;
}
-
- }
- static Empty() {
- object.ReferenceEquals(global::grpc.testing.Proto.Empty.Descriptor, null);
}
+
}
#endregion
diff --git a/src/csharp/Grpc.IntegrationTesting/Grpc.IntegrationTesting.csproj b/src/csharp/Grpc.IntegrationTesting/Grpc.IntegrationTesting.csproj
index 2020a76d39..a5945be922 100644
--- a/src/csharp/Grpc.IntegrationTesting/Grpc.IntegrationTesting.csproj
+++ b/src/csharp/Grpc.IntegrationTesting/Grpc.IntegrationTesting.csproj
@@ -54,6 +54,10 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Google.Apis.Core.1.9.3\lib\portable-net40+sl50+win+wpa81+wp80\Google.Apis.Core.dll</HintPath>
</Reference>
+ <Reference Include="Google.Protobuf, Version=3.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
+ </Reference>
<Reference Include="Microsoft.Threading.Tasks, Version=1.0.12.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll</HintPath>
@@ -74,22 +78,11 @@
<HintPath>..\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
- <Reference Include="Google.ProtocolBuffers">
- <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.521\lib\net40\Google.ProtocolBuffers.dll</HintPath>
- </Reference>
<Reference Include="System.Interactive.Async">
<HintPath>..\packages\Ix-Async.1.2.3\lib\net45\System.Interactive.Async.dll</HintPath>
</Reference>
<Reference Include="System.Net" />
<Reference Include="System.Net.Http" />
- <Reference Include="System.Net.Http.Extensions, Version=2.2.29.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Extensions.dll</HintPath>
- </Reference>
- <Reference Include="System.Net.Http.Primitives, Version=4.2.29.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Primitives.dll</HintPath>
- </Reference>
<Reference Include="System.Net.Http.WebRequest" />
</ItemGroup>
<ItemGroup>
@@ -106,6 +99,7 @@
<Compile Include="TestCredentials.cs" />
<Compile Include="TestGrpc.cs" />
<Compile Include="SslCredentialsTest.cs" />
+ <Compile Include="Test.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
diff --git a/src/csharp/Grpc.IntegrationTesting/InteropClient.cs b/src/csharp/Grpc.IntegrationTesting/InteropClient.cs
index 24c22273fb..8343e54122 100644
--- a/src/csharp/Grpc.IntegrationTesting/InteropClient.cs
+++ b/src/csharp/Grpc.IntegrationTesting/InteropClient.cs
@@ -38,13 +38,11 @@ using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
-using Google.ProtocolBuffers;
-
-using grpc.testing;
+using Google.Protobuf;
using Grpc.Auth;
using Grpc.Core;
using Grpc.Core.Utils;
-
+using Grpc.Testing;
using NUnit.Framework;
namespace Grpc.IntegrationTesting
@@ -183,7 +181,7 @@ namespace Grpc.IntegrationTesting
public static void RunEmptyUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running empty_unary");
- var response = client.EmptyCall(Empty.DefaultInstance);
+ var response = client.EmptyCall(new Empty());
Assert.IsNotNull(response);
Console.WriteLine("Passed!");
}
@@ -191,11 +189,12 @@ namespace Grpc.IntegrationTesting
public static void RunLargeUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running large_unary");
- var request = SimpleRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .SetResponseSize(314159)
- .SetPayload(CreateZerosPayload(271828))
- .Build();
+ var request = new SimpleRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseSize = 314159,
+ Payload = CreateZerosPayload(271828)
+ };
var response = client.UnaryCall(request);
@@ -208,7 +207,7 @@ namespace Grpc.IntegrationTesting
{
Console.WriteLine("running client_streaming");
- var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => StreamingInputCallRequest.CreateBuilder().SetPayload(CreateZerosPayload(size)).Build());
+ var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => new StreamingInputCallRequest { Payload = CreateZerosPayload(size) });
using (var call = client.StreamingInputCall())
{
@@ -226,11 +225,11 @@ namespace Grpc.IntegrationTesting
var bodySizes = new List<int> { 31415, 9, 2653, 58979 };
- var request = StreamingOutputCallRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .AddRangeResponseParameters(bodySizes.ConvertAll(
- (size) => ResponseParameters.CreateBuilder().SetSize(size).Build()))
- .Build();
+ var request = new StreamingOutputCallRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseParameters = { bodySizes.ConvertAll((size) => new ResponseParameters { Size = size }) }
+ };
using (var call = client.StreamingOutputCall(request))
{
@@ -250,37 +249,45 @@ namespace Grpc.IntegrationTesting
using (var call = client.FullDuplexCall())
{
- await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(31415))
- .SetPayload(CreateZerosPayload(27182)).Build());
+ await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseParameters = { new ResponseParameters { Size = 31415 } },
+ Payload = CreateZerosPayload(27182)
+ });
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
- await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(9))
- .SetPayload(CreateZerosPayload(8)).Build());
+ await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseParameters = { new ResponseParameters { Size = 9 } },
+ Payload = CreateZerosPayload(8)
+ });
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length);
- await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(2653))
- .SetPayload(CreateZerosPayload(1828)).Build());
+ await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseParameters = { new ResponseParameters { Size = 2653 } },
+ Payload = CreateZerosPayload(1828)
+ });
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length);
- await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(58979))
- .SetPayload(CreateZerosPayload(45904)).Build());
+ await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseParameters = { new ResponseParameters { Size = 58979 } },
+ Payload = CreateZerosPayload(45904)
+ });
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
@@ -313,13 +320,14 @@ namespace Grpc.IntegrationTesting
credential = credential.CreateScoped(new[] { AuthScope });
client.HeaderInterceptor = AuthInterceptors.FromCredential(credential);
- var request = SimpleRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .SetResponseSize(314159)
- .SetPayload(CreateZerosPayload(271828))
- .SetFillUsername(true)
- .SetFillOauthScope(true)
- .Build();
+ var request = new SimpleRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseSize = 314159,
+ Payload = CreateZerosPayload(271828),
+ FillUsername = true,
+ FillOauthScope = true
+ };
var response = client.UnaryCall(request);
@@ -337,13 +345,14 @@ namespace Grpc.IntegrationTesting
Assert.IsFalse(credential.IsCreateScopedRequired);
client.HeaderInterceptor = AuthInterceptors.FromCredential(credential);
- var request = SimpleRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .SetResponseSize(314159)
- .SetPayload(CreateZerosPayload(271828))
- .SetFillUsername(true)
- .SetFillOauthScope(true)
- .Build();
+ var request = new SimpleRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseSize = 314159,
+ Payload = CreateZerosPayload(271828),
+ FillUsername = true,
+ FillOauthScope = true
+ };
var response = client.UnaryCall(request);
@@ -362,13 +371,14 @@ namespace Grpc.IntegrationTesting
Assert.IsTrue(credential.IsCreateScopedRequired);
client.HeaderInterceptor = AuthInterceptors.FromCredential(credential);
- var request = SimpleRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .SetResponseSize(314159)
- .SetPayload(CreateZerosPayload(271828))
- .SetFillUsername(true)
- .SetFillOauthScope(true)
- .Build();
+ var request = new SimpleRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseSize = 314159,
+ Payload = CreateZerosPayload(271828),
+ FillUsername = true,
+ FillOauthScope = true
+ };
var response = client.UnaryCall(request);
@@ -386,10 +396,11 @@ namespace Grpc.IntegrationTesting
client.HeaderInterceptor = AuthInterceptors.FromAccessToken(oauth2Token);
- var request = SimpleRequest.CreateBuilder()
- .SetFillUsername(true)
- .SetFillOauthScope(true)
- .Build();
+ var request = new SimpleRequest
+ {
+ FillUsername = true,
+ FillOauthScope = true
+ };
var response = client.UnaryCall(request);
@@ -406,10 +417,11 @@ namespace Grpc.IntegrationTesting
string oauth2Token = await credential.GetAccessTokenForRequestAsync();
var headerInterceptor = AuthInterceptors.FromAccessToken(oauth2Token);
- var request = SimpleRequest.CreateBuilder()
- .SetFillUsername(true)
- .SetFillOauthScope(true)
- .Build();
+ var request = new SimpleRequest
+ {
+ FillUsername = true,
+ FillOauthScope = true
+ };
var headers = new Metadata();
headerInterceptor(null, "", headers);
@@ -444,10 +456,12 @@ namespace Grpc.IntegrationTesting
var cts = new CancellationTokenSource();
using (var call = client.FullDuplexCall(cancellationToken: cts.Token))
{
- await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
- .SetResponseType(PayloadType.COMPRESSABLE)
- .AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(31415))
- .SetPayload(CreateZerosPayload(27182)).Build());
+ await call.RequestStream.WriteAsync(new StreamingOutputCallRequest
+ {
+ ResponseType = PayloadType.COMPRESSABLE,
+ ResponseParameters = { new ResponseParameters { Size = 31415 } },
+ Payload = CreateZerosPayload(27182)
+ });
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
@@ -470,8 +484,7 @@ namespace Grpc.IntegrationTesting
{
try
{
- await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
- .SetPayload(CreateZerosPayload(27182)).Build());
+ await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { Payload = CreateZerosPayload(27182) });
}
catch (InvalidOperationException)
{
@@ -488,12 +501,12 @@ namespace Grpc.IntegrationTesting
public static void RunBenchmarkEmptyUnary(TestService.ITestServiceClient client)
{
BenchmarkUtil.RunBenchmark(10000, 10000,
- () => { client.EmptyCall(Empty.DefaultInstance); });
+ () => { client.EmptyCall(new Empty()); });
}
private static Payload CreateZerosPayload(int size)
{
- return Payload.CreateBuilder().SetBody(ByteString.CopyFrom(new byte[size])).Build();
+ return new Payload { Body = ByteString.CopyFrom(new byte[size]) };
}
private static ClientOptions ParseArguments(string[] args)
diff --git a/src/csharp/Grpc.IntegrationTesting/InteropClientServerTest.cs b/src/csharp/Grpc.IntegrationTesting/InteropClientServerTest.cs
index f3158aeb45..7bc17a207f 100644
--- a/src/csharp/Grpc.IntegrationTesting/InteropClientServerTest.cs
+++ b/src/csharp/Grpc.IntegrationTesting/InteropClientServerTest.cs
@@ -36,9 +36,9 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using grpc.testing;
using Grpc.Core;
using Grpc.Core.Utils;
+using Grpc.Testing;
using NUnit.Framework;
namespace Grpc.IntegrationTesting
diff --git a/src/csharp/Grpc.IntegrationTesting/InteropServer.cs b/src/csharp/Grpc.IntegrationTesting/InteropServer.cs
index 0cc8b2cde1..718278f30a 100644
--- a/src/csharp/Grpc.IntegrationTesting/InteropServer.cs
+++ b/src/csharp/Grpc.IntegrationTesting/InteropServer.cs
@@ -37,10 +37,9 @@ using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
-using Google.ProtocolBuffers;
-using grpc.testing;
using Grpc.Core;
using Grpc.Core.Utils;
+using Grpc.Testing;
using NUnit.Framework;
namespace Grpc.IntegrationTesting
diff --git a/src/csharp/Grpc.IntegrationTesting/Messages.cs b/src/csharp/Grpc.IntegrationTesting/Messages.cs
index 386f377f08..a3cbb7d76e 100644
--- a/src/csharp/Grpc.IntegrationTesting/Messages.cs
+++ b/src/csharp/Grpc.IntegrationTesting/Messages.cs
@@ -1,106 +1,58 @@
-// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: messages.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
-using pb = global::Google.ProtocolBuffers;
-using pbc = global::Google.ProtocolBuffers.Collections;
-using pbd = global::Google.ProtocolBuffers.Descriptors;
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
-namespace grpc.testing {
+namespace Grpc.Testing {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Messages {
- #region Extension registration
- public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
- }
- #endregion
- #region Static variables
- internal static pbd::MessageDescriptor internal__static_grpc_testing_Payload__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.Payload, global::grpc.testing.Payload.Builder> internal__static_grpc_testing_Payload__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_testing_SimpleRequest__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.SimpleRequest, global::grpc.testing.SimpleRequest.Builder> internal__static_grpc_testing_SimpleRequest__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_testing_SimpleResponse__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.SimpleResponse, global::grpc.testing.SimpleResponse.Builder> internal__static_grpc_testing_SimpleResponse__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_testing_StreamingInputCallRequest__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallRequest.Builder> internal__static_grpc_testing_StreamingInputCallRequest__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_testing_StreamingInputCallResponse__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingInputCallResponse, global::grpc.testing.StreamingInputCallResponse.Builder> internal__static_grpc_testing_StreamingInputCallResponse__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_testing_ResponseParameters__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.ResponseParameters, global::grpc.testing.ResponseParameters.Builder> internal__static_grpc_testing_ResponseParameters__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_testing_StreamingOutputCallRequest__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallRequest.Builder> internal__static_grpc_testing_StreamingOutputCallRequest__FieldAccessorTable;
- internal static pbd::MessageDescriptor internal__static_grpc_testing_StreamingOutputCallResponse__Descriptor;
- internal static pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingOutputCallResponse, global::grpc.testing.StreamingOutputCallResponse.Builder> internal__static_grpc_testing_StreamingOutputCallResponse__FieldAccessorTable;
- #endregion
#region Descriptor
- public static pbd::FileDescriptor Descriptor {
+ public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
- private static pbd::FileDescriptor descriptor;
+ private static pbr::FileDescriptor descriptor;
static Messages() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "Cg5tZXNzYWdlcy5wcm90bxIMZ3JwYy50ZXN0aW5nIkAKB1BheWxvYWQSJwoE",
- "dHlwZRgBIAEoDjIZLmdycGMudGVzdGluZy5QYXlsb2FkVHlwZRIMCgRib2R5",
- "GAIgASgMIrEBCg1TaW1wbGVSZXF1ZXN0EjAKDXJlc3BvbnNlX3R5cGUYASAB",
- "KA4yGS5ncnBjLnRlc3RpbmcuUGF5bG9hZFR5cGUSFQoNcmVzcG9uc2Vfc2l6",
- "ZRgCIAEoBRImCgdwYXlsb2FkGAMgASgLMhUuZ3JwYy50ZXN0aW5nLlBheWxv",
- "YWQSFQoNZmlsbF91c2VybmFtZRgEIAEoCBIYChBmaWxsX29hdXRoX3Njb3Bl",
- "GAUgASgIIl8KDlNpbXBsZVJlc3BvbnNlEiYKB3BheWxvYWQYASABKAsyFS5n",
- "cnBjLnRlc3RpbmcuUGF5bG9hZBIQCgh1c2VybmFtZRgCIAEoCRITCgtvYXV0",
- "aF9zY29wZRgDIAEoCSJDChlTdHJlYW1pbmdJbnB1dENhbGxSZXF1ZXN0EiYK",
- "B3BheWxvYWQYASABKAsyFS5ncnBjLnRlc3RpbmcuUGF5bG9hZCI9ChpTdHJl",
- "YW1pbmdJbnB1dENhbGxSZXNwb25zZRIfChdhZ2dyZWdhdGVkX3BheWxvYWRf",
- "c2l6ZRgBIAEoBSI3ChJSZXNwb25zZVBhcmFtZXRlcnMSDAoEc2l6ZRgBIAEo",
- "BRITCgtpbnRlcnZhbF91cxgCIAEoBSK1AQoaU3RyZWFtaW5nT3V0cHV0Q2Fs",
- "bFJlcXVlc3QSMAoNcmVzcG9uc2VfdHlwZRgBIAEoDjIZLmdycGMudGVzdGlu",
- "Zy5QYXlsb2FkVHlwZRI9ChNyZXNwb25zZV9wYXJhbWV0ZXJzGAIgAygLMiAu",
- "Z3JwYy50ZXN0aW5nLlJlc3BvbnNlUGFyYW1ldGVycxImCgdwYXlsb2FkGAMg",
- "ASgLMhUuZ3JwYy50ZXN0aW5nLlBheWxvYWQiRQobU3RyZWFtaW5nT3V0cHV0",
- "Q2FsbFJlc3BvbnNlEiYKB3BheWxvYWQYASABKAsyFS5ncnBjLnRlc3Rpbmcu",
- "UGF5bG9hZCo/CgtQYXlsb2FkVHlwZRIQCgxDT01QUkVTU0FCTEUQABISCg5V",
- "TkNPTVBSRVNTQUJMRRABEgoKBlJBTkRPTRAC"));
- pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
- descriptor = root;
- internal__static_grpc_testing_Payload__Descriptor = Descriptor.MessageTypes[0];
- internal__static_grpc_testing_Payload__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.Payload, global::grpc.testing.Payload.Builder>(internal__static_grpc_testing_Payload__Descriptor,
- new string[] { "Type", "Body", });
- internal__static_grpc_testing_SimpleRequest__Descriptor = Descriptor.MessageTypes[1];
- internal__static_grpc_testing_SimpleRequest__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.SimpleRequest, global::grpc.testing.SimpleRequest.Builder>(internal__static_grpc_testing_SimpleRequest__Descriptor,
- new string[] { "ResponseType", "ResponseSize", "Payload", "FillUsername", "FillOauthScope", });
- internal__static_grpc_testing_SimpleResponse__Descriptor = Descriptor.MessageTypes[2];
- internal__static_grpc_testing_SimpleResponse__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.SimpleResponse, global::grpc.testing.SimpleResponse.Builder>(internal__static_grpc_testing_SimpleResponse__Descriptor,
- new string[] { "Payload", "Username", "OauthScope", });
- internal__static_grpc_testing_StreamingInputCallRequest__Descriptor = Descriptor.MessageTypes[3];
- internal__static_grpc_testing_StreamingInputCallRequest__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallRequest.Builder>(internal__static_grpc_testing_StreamingInputCallRequest__Descriptor,
- new string[] { "Payload", });
- internal__static_grpc_testing_StreamingInputCallResponse__Descriptor = Descriptor.MessageTypes[4];
- internal__static_grpc_testing_StreamingInputCallResponse__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingInputCallResponse, global::grpc.testing.StreamingInputCallResponse.Builder>(internal__static_grpc_testing_StreamingInputCallResponse__Descriptor,
- new string[] { "AggregatedPayloadSize", });
- internal__static_grpc_testing_ResponseParameters__Descriptor = Descriptor.MessageTypes[5];
- internal__static_grpc_testing_ResponseParameters__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.ResponseParameters, global::grpc.testing.ResponseParameters.Builder>(internal__static_grpc_testing_ResponseParameters__Descriptor,
- new string[] { "Size", "IntervalUs", });
- internal__static_grpc_testing_StreamingOutputCallRequest__Descriptor = Descriptor.MessageTypes[6];
- internal__static_grpc_testing_StreamingOutputCallRequest__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallRequest.Builder>(internal__static_grpc_testing_StreamingOutputCallRequest__Descriptor,
- new string[] { "ResponseType", "ResponseParameters", "Payload", });
- internal__static_grpc_testing_StreamingOutputCallResponse__Descriptor = Descriptor.MessageTypes[7];
- internal__static_grpc_testing_StreamingOutputCallResponse__FieldAccessorTable =
- new pb::FieldAccess.FieldAccessorTable<global::grpc.testing.StreamingOutputCallResponse, global::grpc.testing.StreamingOutputCallResponse.Builder>(internal__static_grpc_testing_StreamingOutputCallResponse__Descriptor,
- new string[] { "Payload", });
- return null;
- };
- pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
- new pbd::FileDescriptor[] {
- }, assigner);
+ "Cg5tZXNzYWdlcy5wcm90bxIMZ3JwYy50ZXN0aW5nIkAKB1BheWxvYWQSJwoE",
+ "dHlwZRgBIAEoDjIZLmdycGMudGVzdGluZy5QYXlsb2FkVHlwZRIMCgRib2R5",
+ "GAIgASgMIrEBCg1TaW1wbGVSZXF1ZXN0EjAKDXJlc3BvbnNlX3R5cGUYASAB",
+ "KA4yGS5ncnBjLnRlc3RpbmcuUGF5bG9hZFR5cGUSFQoNcmVzcG9uc2Vfc2l6",
+ "ZRgCIAEoBRImCgdwYXlsb2FkGAMgASgLMhUuZ3JwYy50ZXN0aW5nLlBheWxv",
+ "YWQSFQoNZmlsbF91c2VybmFtZRgEIAEoCBIYChBmaWxsX29hdXRoX3Njb3Bl",
+ "GAUgASgIIl8KDlNpbXBsZVJlc3BvbnNlEiYKB3BheWxvYWQYASABKAsyFS5n",
+ "cnBjLnRlc3RpbmcuUGF5bG9hZBIQCgh1c2VybmFtZRgCIAEoCRITCgtvYXV0",
+ "aF9zY29wZRgDIAEoCSJDChlTdHJlYW1pbmdJbnB1dENhbGxSZXF1ZXN0EiYK",
+ "B3BheWxvYWQYASABKAsyFS5ncnBjLnRlc3RpbmcuUGF5bG9hZCI9ChpTdHJl",
+ "YW1pbmdJbnB1dENhbGxSZXNwb25zZRIfChdhZ2dyZWdhdGVkX3BheWxvYWRf",
+ "c2l6ZRgBIAEoBSI3ChJSZXNwb25zZVBhcmFtZXRlcnMSDAoEc2l6ZRgBIAEo",
+ "BRITCgtpbnRlcnZhbF91cxgCIAEoBSK1AQoaU3RyZWFtaW5nT3V0cHV0Q2Fs",
+ "bFJlcXVlc3QSMAoNcmVzcG9uc2VfdHlwZRgBIAEoDjIZLmdycGMudGVzdGlu",
+ "Zy5QYXlsb2FkVHlwZRI9ChNyZXNwb25zZV9wYXJhbWV0ZXJzGAIgAygLMiAu",
+ "Z3JwYy50ZXN0aW5nLlJlc3BvbnNlUGFyYW1ldGVycxImCgdwYXlsb2FkGAMg",
+ "ASgLMhUuZ3JwYy50ZXN0aW5nLlBheWxvYWQiRQobU3RyZWFtaW5nT3V0cHV0",
+ "Q2FsbFJlc3BvbnNlEiYKB3BheWxvYWQYASABKAsyFS5ncnBjLnRlc3Rpbmcu",
+ "UGF5bG9hZCo/CgtQYXlsb2FkVHlwZRIQCgxDT01QUkVTU0FCTEUQABISCg5V",
+ "TkNPTVBSRVNTQUJMRRABEgoKBlJBTkRPTRACYgZwcm90bzM="));
+ descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
+ new pbr::FileDescriptor[] { },
+ new pbr::GeneratedCodeInfo(new[] {typeof(global::Grpc.Testing.PayloadType), }, new pbr::GeneratedCodeInfo[] {
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.Payload), new[]{ "Type", "Body" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.SimpleRequest), new[]{ "ResponseType", "ResponseSize", "Payload", "FillUsername", "FillOauthScope" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.SimpleResponse), new[]{ "Payload", "Username", "OauthScope" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingInputCallRequest), new[]{ "Payload" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingInputCallResponse), new[]{ "AggregatedPayloadSize" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ResponseParameters), new[]{ "Size", "IntervalUs" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingOutputCallRequest), new[]{ "ResponseType", "ResponseParameters", "Payload" }, null, null, null),
+ new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.StreamingOutputCallResponse), new[]{ "Payload" }, null, null, null)
+ }));
}
#endregion
@@ -116,2772 +68,1101 @@ namespace grpc.testing {
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Payload : pb::GeneratedMessage<Payload, Payload.Builder> {
- private Payload() { }
- private static readonly Payload defaultInstance = new Payload().MakeReadOnly();
- private static readonly string[] _payloadFieldNames = new string[] { "body", "type" };
- private static readonly uint[] _payloadFieldTags = new uint[] { 18, 8 };
- public static Payload DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class Payload : pb::IMessage<Payload> {
+ private static readonly pb::MessageParser<Payload> _parser = new pb::MessageParser<Payload>(() => new Payload());
+ public static pb::MessageParser<Payload> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[0]; }
}
- public override Payload DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override Payload ThisMessage {
- get { return this; }
+ public Payload() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_Payload__Descriptor; }
+ partial void OnConstruction();
+
+ public Payload(Payload other) : this() {
+ type_ = other.type_;
+ body_ = other.body_;
}
- protected override pb::FieldAccess.FieldAccessorTable<Payload, Payload.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_Payload__FieldAccessorTable; }
+ public Payload Clone() {
+ return new Payload(this);
}
public const int TypeFieldNumber = 1;
- private bool hasType;
- private global::grpc.testing.PayloadType type_ = global::grpc.testing.PayloadType.COMPRESSABLE;
- public bool HasType {
- get { return hasType; }
- }
- public global::grpc.testing.PayloadType Type {
+ private global::Grpc.Testing.PayloadType type_ = global::Grpc.Testing.PayloadType.COMPRESSABLE;
+ public global::Grpc.Testing.PayloadType Type {
get { return type_; }
+ set {
+ type_ = value;
+ }
}
public const int BodyFieldNumber = 2;
- private bool hasBody;
private pb::ByteString body_ = pb::ByteString.Empty;
- public bool HasBody {
- get { return hasBody; }
- }
public pb::ByteString Body {
get { return body_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ body_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _payloadFieldNames;
- if (hasType) {
- output.WriteEnum(1, field_names[1], (int) Type, Type);
- }
- if (hasBody) {
- output.WriteBytes(2, field_names[0], Body);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as Payload);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasType) {
- size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Type);
- }
- if (hasBody) {
- size += pb::CodedOutputStream.ComputeBytesSize(2, Body);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(Payload other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Type != other.Type) return false;
+ if (Body != other.Body) return false;
+ return true;
}
- public static Payload ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static Payload ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static Payload ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static Payload ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static Payload ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static Payload ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static Payload ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static Payload ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static Payload ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static Payload ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private Payload MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) hash ^= Type.GetHashCode();
+ if (Body.Length != 0) hash ^= Body.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(Payload prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<Payload, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(Payload cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private Payload result;
-
- private Payload PrepareBuilder() {
- if (resultIsReadOnly) {
- Payload original = result;
- result = new Payload();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ output.WriteRawTag(8);
+ output.WriteEnum((int) Type);
}
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override Payload MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
+ if (Body.Length != 0) {
+ output.WriteRawTag(18);
+ output.WriteBytes(Body);
}
+ }
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
+ public int CalculateSize() {
+ int size = 0;
+ if (Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.Payload.Descriptor; }
+ if (Body.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeBytesSize(Body);
}
+ return size;
+ }
- public override Payload DefaultInstanceForType {
- get { return global::grpc.testing.Payload.DefaultInstance; }
+ public void MergeFrom(Payload other) {
+ if (other == null) {
+ return;
}
-
- public override Payload BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ if (other.Type != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ Type = other.Type;
}
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is Payload) {
- return MergeFrom((Payload) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ if (other.Body.Length != 0) {
+ Body = other.Body;
}
+ }
- public override Builder MergeFrom(Payload other) {
- if (other == global::grpc.testing.Payload.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasType) {
- Type = other.Type;
- }
- if (other.HasBody) {
- Body = other.Body;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_payloadFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _payloadFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ type_ = (global::Grpc.Testing.PayloadType) input.ReadEnum();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- object unknown;
- if(input.ReadEnum(ref result.type_, out unknown)) {
- result.hasType = true;
- } else if(unknown is int) {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- unknownFields.MergeVarintField(1, (ulong)(int)unknown);
- }
- break;
- }
- case 18: {
- result.hasBody = input.ReadBytes(ref result.body_);
- break;
- }
+ case 18: {
+ Body = input.ReadBytes();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasType {
- get { return result.hasType; }
- }
- public global::grpc.testing.PayloadType Type {
- get { return result.Type; }
- set { SetType(value); }
- }
- public Builder SetType(global::grpc.testing.PayloadType value) {
- PrepareBuilder();
- result.hasType = true;
- result.type_ = value;
- return this;
- }
- public Builder ClearType() {
- PrepareBuilder();
- result.hasType = false;
- result.type_ = global::grpc.testing.PayloadType.COMPRESSABLE;
- return this;
- }
-
- public bool HasBody {
- get { return result.hasBody; }
- }
- public pb::ByteString Body {
- get { return result.Body; }
- set { SetBody(value); }
}
- public Builder SetBody(pb::ByteString value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasBody = true;
- result.body_ = value;
- return this;
- }
- public Builder ClearBody() {
- PrepareBuilder();
- result.hasBody = false;
- result.body_ = pb::ByteString.Empty;
- return this;
- }
- }
- static Payload() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class SimpleRequest : pb::GeneratedMessage<SimpleRequest, SimpleRequest.Builder> {
- private SimpleRequest() { }
- private static readonly SimpleRequest defaultInstance = new SimpleRequest().MakeReadOnly();
- private static readonly string[] _simpleRequestFieldNames = new string[] { "fill_oauth_scope", "fill_username", "payload", "response_size", "response_type" };
- private static readonly uint[] _simpleRequestFieldTags = new uint[] { 40, 32, 26, 16, 8 };
- public static SimpleRequest DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class SimpleRequest : pb::IMessage<SimpleRequest> {
+ private static readonly pb::MessageParser<SimpleRequest> _parser = new pb::MessageParser<SimpleRequest>(() => new SimpleRequest());
+ public static pb::MessageParser<SimpleRequest> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[1]; }
}
- public override SimpleRequest DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override SimpleRequest ThisMessage {
- get { return this; }
+ public SimpleRequest() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_SimpleRequest__Descriptor; }
+ partial void OnConstruction();
+
+ public SimpleRequest(SimpleRequest other) : this() {
+ responseType_ = other.responseType_;
+ responseSize_ = other.responseSize_;
+ Payload = other.payload_ != null ? other.Payload.Clone() : null;
+ fillUsername_ = other.fillUsername_;
+ fillOauthScope_ = other.fillOauthScope_;
}
- protected override pb::FieldAccess.FieldAccessorTable<SimpleRequest, SimpleRequest.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_SimpleRequest__FieldAccessorTable; }
+ public SimpleRequest Clone() {
+ return new SimpleRequest(this);
}
public const int ResponseTypeFieldNumber = 1;
- private bool hasResponseType;
- private global::grpc.testing.PayloadType responseType_ = global::grpc.testing.PayloadType.COMPRESSABLE;
- public bool HasResponseType {
- get { return hasResponseType; }
- }
- public global::grpc.testing.PayloadType ResponseType {
+ private global::Grpc.Testing.PayloadType responseType_ = global::Grpc.Testing.PayloadType.COMPRESSABLE;
+ public global::Grpc.Testing.PayloadType ResponseType {
get { return responseType_; }
+ set {
+ responseType_ = value;
+ }
}
public const int ResponseSizeFieldNumber = 2;
- private bool hasResponseSize;
private int responseSize_;
- public bool HasResponseSize {
- get { return hasResponseSize; }
- }
public int ResponseSize {
get { return responseSize_; }
+ set {
+ responseSize_ = value;
+ }
}
public const int PayloadFieldNumber = 3;
- private bool hasPayload;
- private global::grpc.testing.Payload payload_;
- public bool HasPayload {
- get { return hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return payload_ ?? global::grpc.testing.Payload.DefaultInstance; }
+ private global::Grpc.Testing.Payload payload_;
+ public global::Grpc.Testing.Payload Payload {
+ get { return payload_; }
+ set {
+ payload_ = value;
+ }
}
public const int FillUsernameFieldNumber = 4;
- private bool hasFillUsername;
private bool fillUsername_;
- public bool HasFillUsername {
- get { return hasFillUsername; }
- }
public bool FillUsername {
get { return fillUsername_; }
+ set {
+ fillUsername_ = value;
+ }
}
public const int FillOauthScopeFieldNumber = 5;
- private bool hasFillOauthScope;
private bool fillOauthScope_;
- public bool HasFillOauthScope {
- get { return hasFillOauthScope; }
- }
public bool FillOauthScope {
get { return fillOauthScope_; }
+ set {
+ fillOauthScope_ = value;
+ }
}
- public override bool IsInitialized {
- get {
- return true;
- }
+ public override bool Equals(object other) {
+ return Equals(other as SimpleRequest);
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _simpleRequestFieldNames;
- if (hasResponseType) {
- output.WriteEnum(1, field_names[4], (int) ResponseType, ResponseType);
- }
- if (hasResponseSize) {
- output.WriteInt32(2, field_names[3], ResponseSize);
- }
- if (hasPayload) {
- output.WriteMessage(3, field_names[2], Payload);
- }
- if (hasFillUsername) {
- output.WriteBool(4, field_names[1], FillUsername);
+ public bool Equals(SimpleRequest other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
- if (hasFillOauthScope) {
- output.WriteBool(5, field_names[0], FillOauthScope);
+ if (ReferenceEquals(other, this)) {
+ return true;
}
- UnknownFields.WriteTo(output);
+ if (ResponseType != other.ResponseType) return false;
+ if (ResponseSize != other.ResponseSize) return false;
+ if (!object.Equals(Payload, other.Payload)) return false;
+ if (FillUsername != other.FillUsername) return false;
+ if (FillOauthScope != other.FillOauthScope) return false;
+ return true;
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasResponseType) {
- size += pb::CodedOutputStream.ComputeEnumSize(1, (int) ResponseType);
- }
- if (hasResponseSize) {
- size += pb::CodedOutputStream.ComputeInt32Size(2, ResponseSize);
- }
- if (hasPayload) {
- size += pb::CodedOutputStream.ComputeMessageSize(3, Payload);
- }
- if (hasFillUsername) {
- size += pb::CodedOutputStream.ComputeBoolSize(4, FillUsername);
- }
- if (hasFillOauthScope) {
- size += pb::CodedOutputStream.ComputeBoolSize(5, FillOauthScope);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
- }
+ public override int GetHashCode() {
+ int hash = 1;
+ if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) hash ^= ResponseType.GetHashCode();
+ if (ResponseSize != 0) hash ^= ResponseSize.GetHashCode();
+ if (payload_ != null) hash ^= Payload.GetHashCode();
+ if (FillUsername != false) hash ^= FillUsername.GetHashCode();
+ if (FillOauthScope != false) hash ^= FillOauthScope.GetHashCode();
+ return hash;
}
- public static SimpleRequest ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static SimpleRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static SimpleRequest ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static SimpleRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static SimpleRequest ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static SimpleRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static SimpleRequest ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static SimpleRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static SimpleRequest ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static SimpleRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private SimpleRequest MakeReadOnly() {
- return this;
- }
-
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(SimpleRequest prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<SimpleRequest, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ output.WriteRawTag(8);
+ output.WriteEnum((int) ResponseType);
}
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
+ if (ResponseSize != 0) {
+ output.WriteRawTag(16);
+ output.WriteInt32(ResponseSize);
}
- internal Builder(SimpleRequest cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
+ if (payload_ != null) {
+ output.WriteRawTag(26);
+ output.WriteMessage(Payload);
}
-
- private bool resultIsReadOnly;
- private SimpleRequest result;
-
- private SimpleRequest PrepareBuilder() {
- if (resultIsReadOnly) {
- SimpleRequest original = result;
- result = new SimpleRequest();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
+ if (FillUsername != false) {
+ output.WriteRawTag(32);
+ output.WriteBool(FillUsername);
}
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
+ if (FillOauthScope != false) {
+ output.WriteRawTag(40);
+ output.WriteBool(FillOauthScope);
}
+ }
- protected override SimpleRequest MessageBeingBuilt {
- get { return PrepareBuilder(); }
+ public int CalculateSize() {
+ int size = 0;
+ if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ResponseType);
}
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
+ if (ResponseSize != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(ResponseSize);
}
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
+ if (payload_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.SimpleRequest.Descriptor; }
+ if (FillUsername != false) {
+ size += 1 + 1;
}
-
- public override SimpleRequest DefaultInstanceForType {
- get { return global::grpc.testing.SimpleRequest.DefaultInstance; }
+ if (FillOauthScope != false) {
+ size += 1 + 1;
}
+ return size;
+ }
- public override SimpleRequest BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ public void MergeFrom(SimpleRequest other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is SimpleRequest) {
- return MergeFrom((SimpleRequest) other);
- } else {
- base.MergeFrom(other);
- return this;
+ if (other.ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ ResponseType = other.ResponseType;
+ }
+ if (other.ResponseSize != 0) {
+ ResponseSize = other.ResponseSize;
+ }
+ if (other.payload_ != null) {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ Payload.MergeFrom(other.Payload);
+ }
+ if (other.FillUsername != false) {
+ FillUsername = other.FillUsername;
}
+ if (other.FillOauthScope != false) {
+ FillOauthScope = other.FillOauthScope;
+ }
+ }
- public override Builder MergeFrom(SimpleRequest other) {
- if (other == global::grpc.testing.SimpleRequest.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasResponseType) {
- ResponseType = other.ResponseType;
- }
- if (other.HasResponseSize) {
- ResponseSize = other.ResponseSize;
- }
- if (other.HasPayload) {
- MergePayload(other.Payload);
- }
- if (other.HasFillUsername) {
- FillUsername = other.FillUsername;
- }
- if (other.HasFillOauthScope) {
- FillOauthScope = other.FillOauthScope;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_simpleRequestFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _simpleRequestFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ responseType_ = (global::Grpc.Testing.PayloadType) input.ReadEnum();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- object unknown;
- if(input.ReadEnum(ref result.responseType_, out unknown)) {
- result.hasResponseType = true;
- } else if(unknown is int) {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- unknownFields.MergeVarintField(1, (ulong)(int)unknown);
- }
- break;
- }
- case 16: {
- result.hasResponseSize = input.ReadInt32(ref result.responseSize_);
- break;
- }
- case 26: {
- global::grpc.testing.Payload.Builder subBuilder = global::grpc.testing.Payload.CreateBuilder();
- if (result.hasPayload) {
- subBuilder.MergeFrom(Payload);
- }
- input.ReadMessage(subBuilder, extensionRegistry);
- Payload = subBuilder.BuildPartial();
- break;
- }
- case 32: {
- result.hasFillUsername = input.ReadBool(ref result.fillUsername_);
- break;
- }
- case 40: {
- result.hasFillOauthScope = input.ReadBool(ref result.fillOauthScope_);
- break;
+ case 16: {
+ ResponseSize = input.ReadInt32();
+ break;
+ }
+ case 26: {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ input.ReadMessage(payload_);
+ break;
+ }
+ case 32: {
+ FillUsername = input.ReadBool();
+ break;
+ }
+ case 40: {
+ FillOauthScope = input.ReadBool();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasResponseType {
- get { return result.hasResponseType; }
- }
- public global::grpc.testing.PayloadType ResponseType {
- get { return result.ResponseType; }
- set { SetResponseType(value); }
- }
- public Builder SetResponseType(global::grpc.testing.PayloadType value) {
- PrepareBuilder();
- result.hasResponseType = true;
- result.responseType_ = value;
- return this;
- }
- public Builder ClearResponseType() {
- PrepareBuilder();
- result.hasResponseType = false;
- result.responseType_ = global::grpc.testing.PayloadType.COMPRESSABLE;
- return this;
- }
-
- public bool HasResponseSize {
- get { return result.hasResponseSize; }
- }
- public int ResponseSize {
- get { return result.ResponseSize; }
- set { SetResponseSize(value); }
- }
- public Builder SetResponseSize(int value) {
- PrepareBuilder();
- result.hasResponseSize = true;
- result.responseSize_ = value;
- return this;
- }
- public Builder ClearResponseSize() {
- PrepareBuilder();
- result.hasResponseSize = false;
- result.responseSize_ = 0;
- return this;
- }
-
- public bool HasPayload {
- get { return result.hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return result.Payload; }
- set { SetPayload(value); }
- }
- public Builder SetPayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = value;
- return this;
- }
- public Builder SetPayload(global::grpc.testing.Payload.Builder builderForValue) {
- pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = builderForValue.Build();
- return this;
- }
- public Builder MergePayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- if (result.hasPayload &&
- result.payload_ != global::grpc.testing.Payload.DefaultInstance) {
- result.payload_ = global::grpc.testing.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial();
- } else {
- result.payload_ = value;
- }
- result.hasPayload = true;
- return this;
- }
- public Builder ClearPayload() {
- PrepareBuilder();
- result.hasPayload = false;
- result.payload_ = null;
- return this;
- }
-
- public bool HasFillUsername {
- get { return result.hasFillUsername; }
- }
- public bool FillUsername {
- get { return result.FillUsername; }
- set { SetFillUsername(value); }
- }
- public Builder SetFillUsername(bool value) {
- PrepareBuilder();
- result.hasFillUsername = true;
- result.fillUsername_ = value;
- return this;
- }
- public Builder ClearFillUsername() {
- PrepareBuilder();
- result.hasFillUsername = false;
- result.fillUsername_ = false;
- return this;
- }
-
- public bool HasFillOauthScope {
- get { return result.hasFillOauthScope; }
- }
- public bool FillOauthScope {
- get { return result.FillOauthScope; }
- set { SetFillOauthScope(value); }
- }
- public Builder SetFillOauthScope(bool value) {
- PrepareBuilder();
- result.hasFillOauthScope = true;
- result.fillOauthScope_ = value;
- return this;
- }
- public Builder ClearFillOauthScope() {
- PrepareBuilder();
- result.hasFillOauthScope = false;
- result.fillOauthScope_ = false;
- return this;
}
}
- static SimpleRequest() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
- }
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class SimpleResponse : pb::GeneratedMessage<SimpleResponse, SimpleResponse.Builder> {
- private SimpleResponse() { }
- private static readonly SimpleResponse defaultInstance = new SimpleResponse().MakeReadOnly();
- private static readonly string[] _simpleResponseFieldNames = new string[] { "oauth_scope", "payload", "username" };
- private static readonly uint[] _simpleResponseFieldTags = new uint[] { 26, 10, 18 };
- public static SimpleResponse DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class SimpleResponse : pb::IMessage<SimpleResponse> {
+ private static readonly pb::MessageParser<SimpleResponse> _parser = new pb::MessageParser<SimpleResponse>(() => new SimpleResponse());
+ public static pb::MessageParser<SimpleResponse> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[2]; }
}
- public override SimpleResponse DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override SimpleResponse ThisMessage {
- get { return this; }
+ public SimpleResponse() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_SimpleResponse__Descriptor; }
+ partial void OnConstruction();
+
+ public SimpleResponse(SimpleResponse other) : this() {
+ Payload = other.payload_ != null ? other.Payload.Clone() : null;
+ username_ = other.username_;
+ oauthScope_ = other.oauthScope_;
}
- protected override pb::FieldAccess.FieldAccessorTable<SimpleResponse, SimpleResponse.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_SimpleResponse__FieldAccessorTable; }
+ public SimpleResponse Clone() {
+ return new SimpleResponse(this);
}
public const int PayloadFieldNumber = 1;
- private bool hasPayload;
- private global::grpc.testing.Payload payload_;
- public bool HasPayload {
- get { return hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return payload_ ?? global::grpc.testing.Payload.DefaultInstance; }
+ private global::Grpc.Testing.Payload payload_;
+ public global::Grpc.Testing.Payload Payload {
+ get { return payload_; }
+ set {
+ payload_ = value;
+ }
}
public const int UsernameFieldNumber = 2;
- private bool hasUsername;
private string username_ = "";
- public bool HasUsername {
- get { return hasUsername; }
- }
public string Username {
get { return username_; }
+ set {
+ username_ = pb::Preconditions.CheckNotNull(value, "value");
+ }
}
public const int OauthScopeFieldNumber = 3;
- private bool hasOauthScope;
private string oauthScope_ = "";
- public bool HasOauthScope {
- get { return hasOauthScope; }
- }
public string OauthScope {
get { return oauthScope_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ oauthScope_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _simpleResponseFieldNames;
- if (hasPayload) {
- output.WriteMessage(1, field_names[1], Payload);
- }
- if (hasUsername) {
- output.WriteString(2, field_names[2], Username);
- }
- if (hasOauthScope) {
- output.WriteString(3, field_names[0], OauthScope);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as SimpleResponse);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasPayload) {
- size += pb::CodedOutputStream.ComputeMessageSize(1, Payload);
- }
- if (hasUsername) {
- size += pb::CodedOutputStream.ComputeStringSize(2, Username);
- }
- if (hasOauthScope) {
- size += pb::CodedOutputStream.ComputeStringSize(3, OauthScope);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(SimpleResponse other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (!object.Equals(Payload, other.Payload)) return false;
+ if (Username != other.Username) return false;
+ if (OauthScope != other.OauthScope) return false;
+ return true;
}
- public static SimpleResponse ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static SimpleResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static SimpleResponse ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static SimpleResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static SimpleResponse ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static SimpleResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static SimpleResponse ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static SimpleResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static SimpleResponse ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static SimpleResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private SimpleResponse MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (payload_ != null) hash ^= Payload.GetHashCode();
+ if (Username.Length != 0) hash ^= Username.GetHashCode();
+ if (OauthScope.Length != 0) hash ^= OauthScope.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(SimpleResponse prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<SimpleResponse, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (payload_ != null) {
+ output.WriteRawTag(10);
+ output.WriteMessage(Payload);
}
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
+ if (Username.Length != 0) {
+ output.WriteRawTag(18);
+ output.WriteString(Username);
}
- internal Builder(SimpleResponse cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
+ if (OauthScope.Length != 0) {
+ output.WriteRawTag(26);
+ output.WriteString(OauthScope);
}
+ }
- private bool resultIsReadOnly;
- private SimpleResponse result;
-
- private SimpleResponse PrepareBuilder() {
- if (resultIsReadOnly) {
- SimpleResponse original = result;
- result = new SimpleResponse();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
+ public int CalculateSize() {
+ int size = 0;
+ if (payload_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
+ if (Username.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(Username);
}
-
- protected override SimpleResponse MessageBeingBuilt {
- get { return PrepareBuilder(); }
+ if (OauthScope.Length != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(OauthScope);
}
+ return size;
+ }
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
+ public void MergeFrom(SimpleResponse other) {
+ if (other == null) {
+ return;
}
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
+ if (other.payload_ != null) {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ Payload.MergeFrom(other.Payload);
}
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.SimpleResponse.Descriptor; }
- }
-
- public override SimpleResponse DefaultInstanceForType {
- get { return global::grpc.testing.SimpleResponse.DefaultInstance; }
+ if (other.Username.Length != 0) {
+ Username = other.Username;
}
-
- public override SimpleResponse BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
- }
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is SimpleResponse) {
- return MergeFrom((SimpleResponse) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ if (other.OauthScope.Length != 0) {
+ OauthScope = other.OauthScope;
}
+ }
- public override Builder MergeFrom(SimpleResponse other) {
- if (other == global::grpc.testing.SimpleResponse.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasPayload) {
- MergePayload(other.Payload);
- }
- if (other.HasUsername) {
- Username = other.Username;
- }
- if (other.HasOauthScope) {
- OauthScope = other.OauthScope;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_simpleResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _simpleResponseFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 10: {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ input.ReadMessage(payload_);
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 10: {
- global::grpc.testing.Payload.Builder subBuilder = global::grpc.testing.Payload.CreateBuilder();
- if (result.hasPayload) {
- subBuilder.MergeFrom(Payload);
- }
- input.ReadMessage(subBuilder, extensionRegistry);
- Payload = subBuilder.BuildPartial();
- break;
- }
- case 18: {
- result.hasUsername = input.ReadString(ref result.username_);
- break;
- }
- case 26: {
- result.hasOauthScope = input.ReadString(ref result.oauthScope_);
- break;
- }
+ case 18: {
+ Username = input.ReadString();
+ break;
+ }
+ case 26: {
+ OauthScope = input.ReadString();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasPayload {
- get { return result.hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return result.Payload; }
- set { SetPayload(value); }
- }
- public Builder SetPayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = value;
- return this;
- }
- public Builder SetPayload(global::grpc.testing.Payload.Builder builderForValue) {
- pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = builderForValue.Build();
- return this;
- }
- public Builder MergePayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- if (result.hasPayload &&
- result.payload_ != global::grpc.testing.Payload.DefaultInstance) {
- result.payload_ = global::grpc.testing.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial();
- } else {
- result.payload_ = value;
- }
- result.hasPayload = true;
- return this;
- }
- public Builder ClearPayload() {
- PrepareBuilder();
- result.hasPayload = false;
- result.payload_ = null;
- return this;
- }
-
- public bool HasUsername {
- get { return result.hasUsername; }
- }
- public string Username {
- get { return result.Username; }
- set { SetUsername(value); }
- }
- public Builder SetUsername(string value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasUsername = true;
- result.username_ = value;
- return this;
- }
- public Builder ClearUsername() {
- PrepareBuilder();
- result.hasUsername = false;
- result.username_ = "";
- return this;
- }
-
- public bool HasOauthScope {
- get { return result.hasOauthScope; }
- }
- public string OauthScope {
- get { return result.OauthScope; }
- set { SetOauthScope(value); }
- }
- public Builder SetOauthScope(string value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasOauthScope = true;
- result.oauthScope_ = value;
- return this;
- }
- public Builder ClearOauthScope() {
- PrepareBuilder();
- result.hasOauthScope = false;
- result.oauthScope_ = "";
- return this;
}
}
- static SimpleResponse() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
- }
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class StreamingInputCallRequest : pb::GeneratedMessage<StreamingInputCallRequest, StreamingInputCallRequest.Builder> {
- private StreamingInputCallRequest() { }
- private static readonly StreamingInputCallRequest defaultInstance = new StreamingInputCallRequest().MakeReadOnly();
- private static readonly string[] _streamingInputCallRequestFieldNames = new string[] { "payload" };
- private static readonly uint[] _streamingInputCallRequestFieldTags = new uint[] { 10 };
- public static StreamingInputCallRequest DefaultInstance {
- get { return defaultInstance; }
- }
+ public sealed partial class StreamingInputCallRequest : pb::IMessage<StreamingInputCallRequest> {
+ private static readonly pb::MessageParser<StreamingInputCallRequest> _parser = new pb::MessageParser<StreamingInputCallRequest>(() => new StreamingInputCallRequest());
+ public static pb::MessageParser<StreamingInputCallRequest> Parser { get { return _parser; } }
- public override StreamingInputCallRequest DefaultInstanceForType {
- get { return DefaultInstance; }
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[3]; }
}
- protected override StreamingInputCallRequest ThisMessage {
- get { return this; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingInputCallRequest__Descriptor; }
+ public StreamingInputCallRequest() {
+ OnConstruction();
}
- protected override pb::FieldAccess.FieldAccessorTable<StreamingInputCallRequest, StreamingInputCallRequest.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingInputCallRequest__FieldAccessorTable; }
- }
+ partial void OnConstruction();
- public const int PayloadFieldNumber = 1;
- private bool hasPayload;
- private global::grpc.testing.Payload payload_;
- public bool HasPayload {
- get { return hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return payload_ ?? global::grpc.testing.Payload.DefaultInstance; }
+ public StreamingInputCallRequest(StreamingInputCallRequest other) : this() {
+ Payload = other.payload_ != null ? other.Payload.Clone() : null;
}
- public override bool IsInitialized {
- get {
- return true;
- }
+ public StreamingInputCallRequest Clone() {
+ return new StreamingInputCallRequest(this);
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _streamingInputCallRequestFieldNames;
- if (hasPayload) {
- output.WriteMessage(1, field_names[0], Payload);
+ public const int PayloadFieldNumber = 1;
+ private global::Grpc.Testing.Payload payload_;
+ public global::Grpc.Testing.Payload Payload {
+ get { return payload_; }
+ set {
+ payload_ = value;
}
- UnknownFields.WriteTo(output);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
+ public override bool Equals(object other) {
+ return Equals(other as StreamingInputCallRequest);
+ }
- size = 0;
- if (hasPayload) {
- size += pb::CodedOutputStream.ComputeMessageSize(1, Payload);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(StreamingInputCallRequest other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
}
+ if (!object.Equals(Payload, other.Payload)) return false;
+ return true;
}
- public static StreamingInputCallRequest ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingInputCallRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingInputCallRequest ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingInputCallRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingInputCallRequest ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingInputCallRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static StreamingInputCallRequest ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static StreamingInputCallRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static StreamingInputCallRequest ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingInputCallRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private StreamingInputCallRequest MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (payload_ != null) hash ^= Payload.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(StreamingInputCallRequest prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<StreamingInputCallRequest, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(StreamingInputCallRequest cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private StreamingInputCallRequest result;
-
- private StreamingInputCallRequest PrepareBuilder() {
- if (resultIsReadOnly) {
- StreamingInputCallRequest original = result;
- result = new StreamingInputCallRequest();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override StreamingInputCallRequest MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.StreamingInputCallRequest.Descriptor; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (payload_ != null) {
+ output.WriteRawTag(10);
+ output.WriteMessage(Payload);
}
+ }
- public override StreamingInputCallRequest DefaultInstanceForType {
- get { return global::grpc.testing.StreamingInputCallRequest.DefaultInstance; }
+ public int CalculateSize() {
+ int size = 0;
+ if (payload_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
+ return size;
+ }
- public override StreamingInputCallRequest BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ public void MergeFrom(StreamingInputCallRequest other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is StreamingInputCallRequest) {
- return MergeFrom((StreamingInputCallRequest) other);
- } else {
- base.MergeFrom(other);
- return this;
+ if (other.payload_ != null) {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ Payload.MergeFrom(other.Payload);
}
+ }
- public override Builder MergeFrom(StreamingInputCallRequest other) {
- if (other == global::grpc.testing.StreamingInputCallRequest.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasPayload) {
- MergePayload(other.Payload);
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_streamingInputCallRequestFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _streamingInputCallRequestFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 10: {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ input.ReadMessage(payload_);
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 10: {
- global::grpc.testing.Payload.Builder subBuilder = global::grpc.testing.Payload.CreateBuilder();
- if (result.hasPayload) {
- subBuilder.MergeFrom(Payload);
- }
- input.ReadMessage(subBuilder, extensionRegistry);
- Payload = subBuilder.BuildPartial();
- break;
- }
- }
- }
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasPayload {
- get { return result.hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return result.Payload; }
- set { SetPayload(value); }
- }
- public Builder SetPayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = value;
- return this;
- }
- public Builder SetPayload(global::grpc.testing.Payload.Builder builderForValue) {
- pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = builderForValue.Build();
- return this;
- }
- public Builder MergePayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- if (result.hasPayload &&
- result.payload_ != global::grpc.testing.Payload.DefaultInstance) {
- result.payload_ = global::grpc.testing.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial();
- } else {
- result.payload_ = value;
}
- result.hasPayload = true;
- return this;
}
- public Builder ClearPayload() {
- PrepareBuilder();
- result.hasPayload = false;
- result.payload_ = null;
- return this;
- }
- }
- static StreamingInputCallRequest() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class StreamingInputCallResponse : pb::GeneratedMessage<StreamingInputCallResponse, StreamingInputCallResponse.Builder> {
- private StreamingInputCallResponse() { }
- private static readonly StreamingInputCallResponse defaultInstance = new StreamingInputCallResponse().MakeReadOnly();
- private static readonly string[] _streamingInputCallResponseFieldNames = new string[] { "aggregated_payload_size" };
- private static readonly uint[] _streamingInputCallResponseFieldTags = new uint[] { 8 };
- public static StreamingInputCallResponse DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class StreamingInputCallResponse : pb::IMessage<StreamingInputCallResponse> {
+ private static readonly pb::MessageParser<StreamingInputCallResponse> _parser = new pb::MessageParser<StreamingInputCallResponse>(() => new StreamingInputCallResponse());
+ public static pb::MessageParser<StreamingInputCallResponse> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[4]; }
}
- public override StreamingInputCallResponse DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override StreamingInputCallResponse ThisMessage {
- get { return this; }
+ public StreamingInputCallResponse() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingInputCallResponse__Descriptor; }
+ partial void OnConstruction();
+
+ public StreamingInputCallResponse(StreamingInputCallResponse other) : this() {
+ aggregatedPayloadSize_ = other.aggregatedPayloadSize_;
}
- protected override pb::FieldAccess.FieldAccessorTable<StreamingInputCallResponse, StreamingInputCallResponse.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingInputCallResponse__FieldAccessorTable; }
+ public StreamingInputCallResponse Clone() {
+ return new StreamingInputCallResponse(this);
}
public const int AggregatedPayloadSizeFieldNumber = 1;
- private bool hasAggregatedPayloadSize;
private int aggregatedPayloadSize_;
- public bool HasAggregatedPayloadSize {
- get { return hasAggregatedPayloadSize; }
- }
public int AggregatedPayloadSize {
get { return aggregatedPayloadSize_; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ set {
+ aggregatedPayloadSize_ = value;
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _streamingInputCallResponseFieldNames;
- if (hasAggregatedPayloadSize) {
- output.WriteInt32(1, field_names[0], AggregatedPayloadSize);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as StreamingInputCallResponse);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasAggregatedPayloadSize) {
- size += pb::CodedOutputStream.ComputeInt32Size(1, AggregatedPayloadSize);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(StreamingInputCallResponse other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
}
+ if (AggregatedPayloadSize != other.AggregatedPayloadSize) return false;
+ return true;
}
- public static StreamingInputCallResponse ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingInputCallResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingInputCallResponse ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingInputCallResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingInputCallResponse ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingInputCallResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static StreamingInputCallResponse ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static StreamingInputCallResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static StreamingInputCallResponse ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingInputCallResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private StreamingInputCallResponse MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (AggregatedPayloadSize != 0) hash ^= AggregatedPayloadSize.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(StreamingInputCallResponse prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<StreamingInputCallResponse, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(StreamingInputCallResponse cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private StreamingInputCallResponse result;
-
- private StreamingInputCallResponse PrepareBuilder() {
- if (resultIsReadOnly) {
- StreamingInputCallResponse original = result;
- result = new StreamingInputCallResponse();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override StreamingInputCallResponse MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.StreamingInputCallResponse.Descriptor; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (AggregatedPayloadSize != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(AggregatedPayloadSize);
}
+ }
- public override StreamingInputCallResponse DefaultInstanceForType {
- get { return global::grpc.testing.StreamingInputCallResponse.DefaultInstance; }
+ public int CalculateSize() {
+ int size = 0;
+ if (AggregatedPayloadSize != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(AggregatedPayloadSize);
}
+ return size;
+ }
- public override StreamingInputCallResponse BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ public void MergeFrom(StreamingInputCallResponse other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is StreamingInputCallResponse) {
- return MergeFrom((StreamingInputCallResponse) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ if (other.AggregatedPayloadSize != 0) {
+ AggregatedPayloadSize = other.AggregatedPayloadSize;
}
+ }
- public override Builder MergeFrom(StreamingInputCallResponse other) {
- if (other == global::grpc.testing.StreamingInputCallResponse.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasAggregatedPayloadSize) {
- AggregatedPayloadSize = other.AggregatedPayloadSize;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_streamingInputCallResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _streamingInputCallResponseFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
- }
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- result.hasAggregatedPayloadSize = input.ReadInt32(ref result.aggregatedPayloadSize_);
- break;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ AggregatedPayloadSize = input.ReadInt32();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasAggregatedPayloadSize {
- get { return result.hasAggregatedPayloadSize; }
- }
- public int AggregatedPayloadSize {
- get { return result.AggregatedPayloadSize; }
- set { SetAggregatedPayloadSize(value); }
- }
- public Builder SetAggregatedPayloadSize(int value) {
- PrepareBuilder();
- result.hasAggregatedPayloadSize = true;
- result.aggregatedPayloadSize_ = value;
- return this;
}
- public Builder ClearAggregatedPayloadSize() {
- PrepareBuilder();
- result.hasAggregatedPayloadSize = false;
- result.aggregatedPayloadSize_ = 0;
- return this;
- }
- }
- static StreamingInputCallResponse() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class ResponseParameters : pb::GeneratedMessage<ResponseParameters, ResponseParameters.Builder> {
- private ResponseParameters() { }
- private static readonly ResponseParameters defaultInstance = new ResponseParameters().MakeReadOnly();
- private static readonly string[] _responseParametersFieldNames = new string[] { "interval_us", "size" };
- private static readonly uint[] _responseParametersFieldTags = new uint[] { 16, 8 };
- public static ResponseParameters DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class ResponseParameters : pb::IMessage<ResponseParameters> {
+ private static readonly pb::MessageParser<ResponseParameters> _parser = new pb::MessageParser<ResponseParameters>(() => new ResponseParameters());
+ public static pb::MessageParser<ResponseParameters> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[5]; }
}
- public override ResponseParameters DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override ResponseParameters ThisMessage {
- get { return this; }
+ public ResponseParameters() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_ResponseParameters__Descriptor; }
+ partial void OnConstruction();
+
+ public ResponseParameters(ResponseParameters other) : this() {
+ size_ = other.size_;
+ intervalUs_ = other.intervalUs_;
}
- protected override pb::FieldAccess.FieldAccessorTable<ResponseParameters, ResponseParameters.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_ResponseParameters__FieldAccessorTable; }
+ public ResponseParameters Clone() {
+ return new ResponseParameters(this);
}
public const int SizeFieldNumber = 1;
- private bool hasSize;
private int size_;
- public bool HasSize {
- get { return hasSize; }
- }
public int Size {
get { return size_; }
+ set {
+ size_ = value;
+ }
}
public const int IntervalUsFieldNumber = 2;
- private bool hasIntervalUs;
private int intervalUs_;
- public bool HasIntervalUs {
- get { return hasIntervalUs; }
- }
public int IntervalUs {
get { return intervalUs_; }
+ set {
+ intervalUs_ = value;
+ }
}
- public override bool IsInitialized {
- get {
- return true;
- }
+ public override bool Equals(object other) {
+ return Equals(other as ResponseParameters);
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _responseParametersFieldNames;
- if (hasSize) {
- output.WriteInt32(1, field_names[1], Size);
+ public bool Equals(ResponseParameters other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
}
- if (hasIntervalUs) {
- output.WriteInt32(2, field_names[0], IntervalUs);
+ if (ReferenceEquals(other, this)) {
+ return true;
}
- UnknownFields.WriteTo(output);
+ if (Size != other.Size) return false;
+ if (IntervalUs != other.IntervalUs) return false;
+ return true;
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasSize) {
- size += pb::CodedOutputStream.ComputeInt32Size(1, Size);
- }
- if (hasIntervalUs) {
- size += pb::CodedOutputStream.ComputeInt32Size(2, IntervalUs);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
- }
+ public override int GetHashCode() {
+ int hash = 1;
+ if (Size != 0) hash ^= Size.GetHashCode();
+ if (IntervalUs != 0) hash ^= IntervalUs.GetHashCode();
+ return hash;
}
- public static ResponseParameters ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static ResponseParameters ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static ResponseParameters ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static ResponseParameters ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static ResponseParameters ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static ResponseParameters ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static ResponseParameters ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static ResponseParameters ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static ResponseParameters ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- public static ResponseParameters ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private ResponseParameters MakeReadOnly() {
- return this;
- }
-
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(ResponseParameters prototype) {
- return new Builder(prototype);
- }
-
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<ResponseParameters, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(ResponseParameters cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
- private bool resultIsReadOnly;
- private ResponseParameters result;
-
- private ResponseParameters PrepareBuilder() {
- if (resultIsReadOnly) {
- ResponseParameters original = result;
- result = new ResponseParameters();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (Size != 0) {
+ output.WriteRawTag(8);
+ output.WriteInt32(Size);
}
-
- protected override ResponseParameters MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
+ if (IntervalUs != 0) {
+ output.WriteRawTag(16);
+ output.WriteInt32(IntervalUs);
}
+ }
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
+ public int CalculateSize() {
+ int size = 0;
+ if (Size != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Size);
}
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.ResponseParameters.Descriptor; }
+ if (IntervalUs != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(IntervalUs);
}
+ return size;
+ }
- public override ResponseParameters DefaultInstanceForType {
- get { return global::grpc.testing.ResponseParameters.DefaultInstance; }
+ public void MergeFrom(ResponseParameters other) {
+ if (other == null) {
+ return;
}
-
- public override ResponseParameters BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ if (other.Size != 0) {
+ Size = other.Size;
}
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is ResponseParameters) {
- return MergeFrom((ResponseParameters) other);
- } else {
- base.MergeFrom(other);
- return this;
- }
+ if (other.IntervalUs != 0) {
+ IntervalUs = other.IntervalUs;
}
+ }
- public override Builder MergeFrom(ResponseParameters other) {
- if (other == global::grpc.testing.ResponseParameters.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasSize) {
- Size = other.Size;
- }
- if (other.HasIntervalUs) {
- IntervalUs = other.IntervalUs;
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_responseParametersFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _responseParametersFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ Size = input.ReadInt32();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- result.hasSize = input.ReadInt32(ref result.size_);
- break;
- }
- case 16: {
- result.hasIntervalUs = input.ReadInt32(ref result.intervalUs_);
- break;
- }
+ case 16: {
+ IntervalUs = input.ReadInt32();
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasSize {
- get { return result.hasSize; }
- }
- public int Size {
- get { return result.Size; }
- set { SetSize(value); }
- }
- public Builder SetSize(int value) {
- PrepareBuilder();
- result.hasSize = true;
- result.size_ = value;
- return this;
- }
- public Builder ClearSize() {
- PrepareBuilder();
- result.hasSize = false;
- result.size_ = 0;
- return this;
- }
-
- public bool HasIntervalUs {
- get { return result.hasIntervalUs; }
}
- public int IntervalUs {
- get { return result.IntervalUs; }
- set { SetIntervalUs(value); }
- }
- public Builder SetIntervalUs(int value) {
- PrepareBuilder();
- result.hasIntervalUs = true;
- result.intervalUs_ = value;
- return this;
- }
- public Builder ClearIntervalUs() {
- PrepareBuilder();
- result.hasIntervalUs = false;
- result.intervalUs_ = 0;
- return this;
- }
- }
- static ResponseParameters() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
}
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class StreamingOutputCallRequest : pb::GeneratedMessage<StreamingOutputCallRequest, StreamingOutputCallRequest.Builder> {
- private StreamingOutputCallRequest() { }
- private static readonly StreamingOutputCallRequest defaultInstance = new StreamingOutputCallRequest().MakeReadOnly();
- private static readonly string[] _streamingOutputCallRequestFieldNames = new string[] { "payload", "response_parameters", "response_type" };
- private static readonly uint[] _streamingOutputCallRequestFieldTags = new uint[] { 26, 18, 8 };
- public static StreamingOutputCallRequest DefaultInstance {
- get { return defaultInstance; }
+ public sealed partial class StreamingOutputCallRequest : pb::IMessage<StreamingOutputCallRequest> {
+ private static readonly pb::MessageParser<StreamingOutputCallRequest> _parser = new pb::MessageParser<StreamingOutputCallRequest>(() => new StreamingOutputCallRequest());
+ public static pb::MessageParser<StreamingOutputCallRequest> Parser { get { return _parser; } }
+
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[6]; }
}
- public override StreamingOutputCallRequest DefaultInstanceForType {
- get { return DefaultInstance; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- protected override StreamingOutputCallRequest ThisMessage {
- get { return this; }
+ public StreamingOutputCallRequest() {
+ OnConstruction();
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingOutputCallRequest__Descriptor; }
+ partial void OnConstruction();
+
+ public StreamingOutputCallRequest(StreamingOutputCallRequest other) : this() {
+ responseType_ = other.responseType_;
+ responseParameters_ = other.responseParameters_.Clone();
+ Payload = other.payload_ != null ? other.Payload.Clone() : null;
}
- protected override pb::FieldAccess.FieldAccessorTable<StreamingOutputCallRequest, StreamingOutputCallRequest.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingOutputCallRequest__FieldAccessorTable; }
+ public StreamingOutputCallRequest Clone() {
+ return new StreamingOutputCallRequest(this);
}
public const int ResponseTypeFieldNumber = 1;
- private bool hasResponseType;
- private global::grpc.testing.PayloadType responseType_ = global::grpc.testing.PayloadType.COMPRESSABLE;
- public bool HasResponseType {
- get { return hasResponseType; }
- }
- public global::grpc.testing.PayloadType ResponseType {
+ private global::Grpc.Testing.PayloadType responseType_ = global::Grpc.Testing.PayloadType.COMPRESSABLE;
+ public global::Grpc.Testing.PayloadType ResponseType {
get { return responseType_; }
+ set {
+ responseType_ = value;
+ }
}
public const int ResponseParametersFieldNumber = 2;
- private pbc::PopsicleList<global::grpc.testing.ResponseParameters> responseParameters_ = new pbc::PopsicleList<global::grpc.testing.ResponseParameters>();
- public scg::IList<global::grpc.testing.ResponseParameters> ResponseParametersList {
+ private static readonly pb::FieldCodec<global::Grpc.Testing.ResponseParameters> _repeated_responseParameters_codec
+ = pb::FieldCodec.ForMessage(18, global::Grpc.Testing.ResponseParameters.Parser);
+ private readonly pbc::RepeatedField<global::Grpc.Testing.ResponseParameters> responseParameters_ = new pbc::RepeatedField<global::Grpc.Testing.ResponseParameters>();
+ public pbc::RepeatedField<global::Grpc.Testing.ResponseParameters> ResponseParameters {
get { return responseParameters_; }
}
- public int ResponseParametersCount {
- get { return responseParameters_.Count; }
- }
- public global::grpc.testing.ResponseParameters GetResponseParameters(int index) {
- return responseParameters_[index];
- }
public const int PayloadFieldNumber = 3;
- private bool hasPayload;
- private global::grpc.testing.Payload payload_;
- public bool HasPayload {
- get { return hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return payload_ ?? global::grpc.testing.Payload.DefaultInstance; }
- }
-
- public override bool IsInitialized {
- get {
- return true;
+ private global::Grpc.Testing.Payload payload_;
+ public global::Grpc.Testing.Payload Payload {
+ get { return payload_; }
+ set {
+ payload_ = value;
}
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _streamingOutputCallRequestFieldNames;
- if (hasResponseType) {
- output.WriteEnum(1, field_names[2], (int) ResponseType, ResponseType);
- }
- if (responseParameters_.Count > 0) {
- output.WriteMessageArray(2, field_names[1], responseParameters_);
- }
- if (hasPayload) {
- output.WriteMessage(3, field_names[0], Payload);
- }
- UnknownFields.WriteTo(output);
+ public override bool Equals(object other) {
+ return Equals(other as StreamingOutputCallRequest);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasResponseType) {
- size += pb::CodedOutputStream.ComputeEnumSize(1, (int) ResponseType);
- }
- foreach (global::grpc.testing.ResponseParameters element in ResponseParametersList) {
- size += pb::CodedOutputStream.ComputeMessageSize(2, element);
- }
- if (hasPayload) {
- size += pb::CodedOutputStream.ComputeMessageSize(3, Payload);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(StreamingOutputCallRequest other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
}
+ if (ResponseType != other.ResponseType) return false;
+ if(!responseParameters_.Equals(other.responseParameters_)) return false;
+ if (!object.Equals(Payload, other.Payload)) return false;
+ return true;
}
- public static StreamingOutputCallRequest ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingOutputCallRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private StreamingOutputCallRequest MakeReadOnly() {
- responseParameters_.MakeReadOnly();
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) hash ^= ResponseType.GetHashCode();
+ hash ^= responseParameters_.GetHashCode();
+ if (payload_ != null) hash ^= Payload.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(StreamingOutputCallRequest prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<StreamingOutputCallRequest, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(StreamingOutputCallRequest cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private StreamingOutputCallRequest result;
-
- private StreamingOutputCallRequest PrepareBuilder() {
- if (resultIsReadOnly) {
- StreamingOutputCallRequest original = result;
- result = new StreamingOutputCallRequest();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ output.WriteRawTag(8);
+ output.WriteEnum((int) ResponseType);
}
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override StreamingOutputCallRequest MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
+ responseParameters_.WriteTo(output, _repeated_responseParameters_codec);
+ if (payload_ != null) {
+ output.WriteRawTag(26);
+ output.WriteMessage(Payload);
}
+ }
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
+ public int CalculateSize() {
+ int size = 0;
+ if (ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ResponseType);
}
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.StreamingOutputCallRequest.Descriptor; }
+ size += responseParameters_.CalculateSize(_repeated_responseParameters_codec);
+ if (payload_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
+ return size;
+ }
- public override StreamingOutputCallRequest DefaultInstanceForType {
- get { return global::grpc.testing.StreamingOutputCallRequest.DefaultInstance; }
+ public void MergeFrom(StreamingOutputCallRequest other) {
+ if (other == null) {
+ return;
}
-
- public override StreamingOutputCallRequest BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ if (other.ResponseType != global::Grpc.Testing.PayloadType.COMPRESSABLE) {
+ ResponseType = other.ResponseType;
}
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is StreamingOutputCallRequest) {
- return MergeFrom((StreamingOutputCallRequest) other);
- } else {
- base.MergeFrom(other);
- return this;
+ responseParameters_.Add(other.responseParameters_);
+ if (other.payload_ != null) {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ Payload.MergeFrom(other.Payload);
}
+ }
- public override Builder MergeFrom(StreamingOutputCallRequest other) {
- if (other == global::grpc.testing.StreamingOutputCallRequest.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasResponseType) {
- ResponseType = other.ResponseType;
- }
- if (other.responseParameters_.Count != 0) {
- result.responseParameters_.Add(other.responseParameters_);
- }
- if (other.HasPayload) {
- MergePayload(other.Payload);
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_streamingOutputCallRequestFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _streamingOutputCallRequestFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 8: {
+ responseType_ = (global::Grpc.Testing.PayloadType) input.ReadEnum();
+ break;
}
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 8: {
- object unknown;
- if(input.ReadEnum(ref result.responseType_, out unknown)) {
- result.hasResponseType = true;
- } else if(unknown is int) {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- unknownFields.MergeVarintField(1, (ulong)(int)unknown);
- }
- break;
- }
- case 18: {
- input.ReadMessageArray(tag, field_name, result.responseParameters_, global::grpc.testing.ResponseParameters.DefaultInstance, extensionRegistry);
- break;
- }
- case 26: {
- global::grpc.testing.Payload.Builder subBuilder = global::grpc.testing.Payload.CreateBuilder();
- if (result.hasPayload) {
- subBuilder.MergeFrom(Payload);
- }
- input.ReadMessage(subBuilder, extensionRegistry);
- Payload = subBuilder.BuildPartial();
- break;
+ case 18: {
+ responseParameters_.AddEntriesFrom(input, _repeated_responseParameters_codec);
+ break;
+ }
+ case 26: {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ input.ReadMessage(payload_);
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasResponseType {
- get { return result.hasResponseType; }
- }
- public global::grpc.testing.PayloadType ResponseType {
- get { return result.ResponseType; }
- set { SetResponseType(value); }
- }
- public Builder SetResponseType(global::grpc.testing.PayloadType value) {
- PrepareBuilder();
- result.hasResponseType = true;
- result.responseType_ = value;
- return this;
- }
- public Builder ClearResponseType() {
- PrepareBuilder();
- result.hasResponseType = false;
- result.responseType_ = global::grpc.testing.PayloadType.COMPRESSABLE;
- return this;
- }
-
- public pbc::IPopsicleList<global::grpc.testing.ResponseParameters> ResponseParametersList {
- get { return PrepareBuilder().responseParameters_; }
- }
- public int ResponseParametersCount {
- get { return result.ResponseParametersCount; }
- }
- public global::grpc.testing.ResponseParameters GetResponseParameters(int index) {
- return result.GetResponseParameters(index);
- }
- public Builder SetResponseParameters(int index, global::grpc.testing.ResponseParameters value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.responseParameters_[index] = value;
- return this;
- }
- public Builder SetResponseParameters(int index, global::grpc.testing.ResponseParameters.Builder builderForValue) {
- pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
- PrepareBuilder();
- result.responseParameters_[index] = builderForValue.Build();
- return this;
- }
- public Builder AddResponseParameters(global::grpc.testing.ResponseParameters value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.responseParameters_.Add(value);
- return this;
- }
- public Builder AddResponseParameters(global::grpc.testing.ResponseParameters.Builder builderForValue) {
- pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
- PrepareBuilder();
- result.responseParameters_.Add(builderForValue.Build());
- return this;
- }
- public Builder AddRangeResponseParameters(scg::IEnumerable<global::grpc.testing.ResponseParameters> values) {
- PrepareBuilder();
- result.responseParameters_.Add(values);
- return this;
- }
- public Builder ClearResponseParameters() {
- PrepareBuilder();
- result.responseParameters_.Clear();
- return this;
- }
-
- public bool HasPayload {
- get { return result.hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return result.Payload; }
- set { SetPayload(value); }
- }
- public Builder SetPayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = value;
- return this;
- }
- public Builder SetPayload(global::grpc.testing.Payload.Builder builderForValue) {
- pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = builderForValue.Build();
- return this;
- }
- public Builder MergePayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- if (result.hasPayload &&
- result.payload_ != global::grpc.testing.Payload.DefaultInstance) {
- result.payload_ = global::grpc.testing.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial();
- } else {
- result.payload_ = value;
- }
- result.hasPayload = true;
- return this;
- }
- public Builder ClearPayload() {
- PrepareBuilder();
- result.hasPayload = false;
- result.payload_ = null;
- return this;
}
}
- static StreamingOutputCallRequest() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
- }
+
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class StreamingOutputCallResponse : pb::GeneratedMessage<StreamingOutputCallResponse, StreamingOutputCallResponse.Builder> {
- private StreamingOutputCallResponse() { }
- private static readonly StreamingOutputCallResponse defaultInstance = new StreamingOutputCallResponse().MakeReadOnly();
- private static readonly string[] _streamingOutputCallResponseFieldNames = new string[] { "payload" };
- private static readonly uint[] _streamingOutputCallResponseFieldTags = new uint[] { 10 };
- public static StreamingOutputCallResponse DefaultInstance {
- get { return defaultInstance; }
- }
+ public sealed partial class StreamingOutputCallResponse : pb::IMessage<StreamingOutputCallResponse> {
+ private static readonly pb::MessageParser<StreamingOutputCallResponse> _parser = new pb::MessageParser<StreamingOutputCallResponse>(() => new StreamingOutputCallResponse());
+ public static pb::MessageParser<StreamingOutputCallResponse> Parser { get { return _parser; } }
- public override StreamingOutputCallResponse DefaultInstanceForType {
- get { return DefaultInstance; }
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::Grpc.Testing.Messages.Descriptor.MessageTypes[7]; }
}
- protected override StreamingOutputCallResponse ThisMessage {
- get { return this; }
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
}
- public static pbd::MessageDescriptor Descriptor {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingOutputCallResponse__Descriptor; }
+ public StreamingOutputCallResponse() {
+ OnConstruction();
}
- protected override pb::FieldAccess.FieldAccessorTable<StreamingOutputCallResponse, StreamingOutputCallResponse.Builder> InternalFieldAccessors {
- get { return global::grpc.testing.Messages.internal__static_grpc_testing_StreamingOutputCallResponse__FieldAccessorTable; }
- }
+ partial void OnConstruction();
- public const int PayloadFieldNumber = 1;
- private bool hasPayload;
- private global::grpc.testing.Payload payload_;
- public bool HasPayload {
- get { return hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return payload_ ?? global::grpc.testing.Payload.DefaultInstance; }
+ public StreamingOutputCallResponse(StreamingOutputCallResponse other) : this() {
+ Payload = other.payload_ != null ? other.Payload.Clone() : null;
}
- public override bool IsInitialized {
- get {
- return true;
- }
+ public StreamingOutputCallResponse Clone() {
+ return new StreamingOutputCallResponse(this);
}
- public override void WriteTo(pb::ICodedOutputStream output) {
- int size = SerializedSize;
- string[] field_names = _streamingOutputCallResponseFieldNames;
- if (hasPayload) {
- output.WriteMessage(1, field_names[0], Payload);
+ public const int PayloadFieldNumber = 1;
+ private global::Grpc.Testing.Payload payload_;
+ public global::Grpc.Testing.Payload Payload {
+ get { return payload_; }
+ set {
+ payload_ = value;
}
- UnknownFields.WriteTo(output);
}
- private int memoizedSerializedSize = -1;
- public override int SerializedSize {
- get {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
+ public override bool Equals(object other) {
+ return Equals(other as StreamingOutputCallResponse);
+ }
- size = 0;
- if (hasPayload) {
- size += pb::CodedOutputStream.ComputeMessageSize(1, Payload);
- }
- size += UnknownFields.SerializedSize;
- memoizedSerializedSize = size;
- return size;
+ public bool Equals(StreamingOutputCallResponse other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
}
+ if (!object.Equals(Payload, other.Payload)) return false;
+ return true;
}
- public static StreamingOutputCallResponse ParseFrom(pb::ByteString data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseFrom(byte[] data) {
- return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseFrom(global::System.IO.Stream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseDelimitedFrom(global::System.IO.Stream input) {
- return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
- return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseFrom(pb::ICodedInputStream input) {
- return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
- }
- public static StreamingOutputCallResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
- }
- private StreamingOutputCallResponse MakeReadOnly() {
- return this;
+ public override int GetHashCode() {
+ int hash = 1;
+ if (payload_ != null) hash ^= Payload.GetHashCode();
+ return hash;
}
- public static Builder CreateBuilder() { return new Builder(); }
- public override Builder ToBuilder() { return CreateBuilder(this); }
- public override Builder CreateBuilderForType() { return new Builder(); }
- public static Builder CreateBuilder(StreamingOutputCallResponse prototype) {
- return new Builder(prototype);
+ public override string ToString() {
+ return pb::JsonFormatter.Default.Format(this);
}
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- public sealed partial class Builder : pb::GeneratedBuilder<StreamingOutputCallResponse, Builder> {
- protected override Builder ThisBuilder {
- get { return this; }
- }
- public Builder() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- }
- internal Builder(StreamingOutputCallResponse cloneFrom) {
- result = cloneFrom;
- resultIsReadOnly = true;
- }
-
- private bool resultIsReadOnly;
- private StreamingOutputCallResponse result;
-
- private StreamingOutputCallResponse PrepareBuilder() {
- if (resultIsReadOnly) {
- StreamingOutputCallResponse original = result;
- result = new StreamingOutputCallResponse();
- resultIsReadOnly = false;
- MergeFrom(original);
- }
- return result;
- }
-
- public override bool IsInitialized {
- get { return result.IsInitialized; }
- }
-
- protected override StreamingOutputCallResponse MessageBeingBuilt {
- get { return PrepareBuilder(); }
- }
-
- public override Builder Clear() {
- result = DefaultInstance;
- resultIsReadOnly = true;
- return this;
- }
-
- public override Builder Clone() {
- if (resultIsReadOnly) {
- return new Builder(result);
- } else {
- return new Builder().MergeFrom(result);
- }
- }
-
- public override pbd::MessageDescriptor DescriptorForType {
- get { return global::grpc.testing.StreamingOutputCallResponse.Descriptor; }
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (payload_ != null) {
+ output.WriteRawTag(10);
+ output.WriteMessage(Payload);
}
+ }
- public override StreamingOutputCallResponse DefaultInstanceForType {
- get { return global::grpc.testing.StreamingOutputCallResponse.DefaultInstance; }
+ public int CalculateSize() {
+ int size = 0;
+ if (payload_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
+ return size;
+ }
- public override StreamingOutputCallResponse BuildPartial() {
- if (resultIsReadOnly) {
- return result;
- }
- resultIsReadOnly = true;
- return result.MakeReadOnly();
+ public void MergeFrom(StreamingOutputCallResponse other) {
+ if (other == null) {
+ return;
}
-
- public override Builder MergeFrom(pb::IMessage other) {
- if (other is StreamingOutputCallResponse) {
- return MergeFrom((StreamingOutputCallResponse) other);
- } else {
- base.MergeFrom(other);
- return this;
+ if (other.payload_ != null) {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ Payload.MergeFrom(other.Payload);
}
+ }
- public override Builder MergeFrom(StreamingOutputCallResponse other) {
- if (other == global::grpc.testing.StreamingOutputCallResponse.DefaultInstance) return this;
- PrepareBuilder();
- if (other.HasPayload) {
- MergePayload(other.Payload);
- }
- this.MergeUnknownFields(other.UnknownFields);
- return this;
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input) {
- return MergeFrom(input, pb::ExtensionRegistry.Empty);
- }
-
- public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
- PrepareBuilder();
- pb::UnknownFieldSet.Builder unknownFields = null;
- uint tag;
- string field_name;
- while (input.ReadTag(out tag, out field_name)) {
- if(tag == 0 && field_name != null) {
- int field_ordinal = global::System.Array.BinarySearch(_streamingOutputCallResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
- if(field_ordinal >= 0)
- tag = _streamingOutputCallResponseFieldTags[field_ordinal];
- else {
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- continue;
- }
- }
- switch (tag) {
- case 0: {
- throw pb::InvalidProtocolBufferException.InvalidTag();
- }
- default: {
- if (pb::WireFormat.IsEndGroupTag(tag)) {
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
- if (unknownFields == null) {
- unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
- }
- ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
- break;
- }
- case 10: {
- global::grpc.testing.Payload.Builder subBuilder = global::grpc.testing.Payload.CreateBuilder();
- if (result.hasPayload) {
- subBuilder.MergeFrom(Payload);
- }
- input.ReadMessage(subBuilder, extensionRegistry);
- Payload = subBuilder.BuildPartial();
- break;
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ input.SkipLastField();
+ break;
+ case 10: {
+ if (payload_ == null) {
+ payload_ = new global::Grpc.Testing.Payload();
}
+ input.ReadMessage(payload_);
+ break;
}
}
-
- if (unknownFields != null) {
- this.UnknownFields = unknownFields.Build();
- }
- return this;
- }
-
-
- public bool HasPayload {
- get { return result.hasPayload; }
- }
- public global::grpc.testing.Payload Payload {
- get { return result.Payload; }
- set { SetPayload(value); }
- }
- public Builder SetPayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = value;
- return this;
- }
- public Builder SetPayload(global::grpc.testing.Payload.Builder builderForValue) {
- pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
- PrepareBuilder();
- result.hasPayload = true;
- result.payload_ = builderForValue.Build();
- return this;
- }
- public Builder MergePayload(global::grpc.testing.Payload value) {
- pb::ThrowHelper.ThrowIfNull(value, "value");
- PrepareBuilder();
- if (result.hasPayload &&
- result.payload_ != global::grpc.testing.Payload.DefaultInstance) {
- result.payload_ = global::grpc.testing.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial();
- } else {
- result.payload_ = value;
- }
- result.hasPayload = true;
- return this;
- }
- public Builder ClearPayload() {
- PrepareBuilder();
- result.hasPayload = false;
- result.payload_ = null;
- return this;
}
}
- static StreamingOutputCallResponse() {
- object.ReferenceEquals(global::grpc.testing.Messages.Descriptor, null);
- }
+
}
#endregion
diff --git a/src/csharp/Grpc.IntegrationTesting/SslCredentialsTest.cs b/src/csharp/Grpc.IntegrationTesting/SslCredentialsTest.cs
index 842795374f..37b2518c21 100644
--- a/src/csharp/Grpc.IntegrationTesting/SslCredentialsTest.cs
+++ b/src/csharp/Grpc.IntegrationTesting/SslCredentialsTest.cs
@@ -37,9 +37,9 @@ using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using grpc.testing;
using Grpc.Core;
using Grpc.Core.Utils;
+using Grpc.Testing;
using NUnit.Framework;
namespace Grpc.IntegrationTesting
@@ -92,7 +92,7 @@ namespace Grpc.IntegrationTesting
[Test]
public void AuthenticatedClientAndServer()
{
- var response = client.UnaryCall(SimpleRequest.CreateBuilder().SetResponseSize(10).Build());
+ var response = client.UnaryCall(new SimpleRequest { ResponseSize = 10 });
Assert.AreEqual(10, response.Payload.Body.Length);
}
}
diff --git a/src/csharp/Grpc.IntegrationTesting/Test.cs b/src/csharp/Grpc.IntegrationTesting/Test.cs
new file mode 100644
index 0000000000..466ec57d3d
--- /dev/null
+++ b/src/csharp/Grpc.IntegrationTesting/Test.cs
@@ -0,0 +1,48 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: test.proto
+#pragma warning disable 1591, 0612, 3021
+#region Designer generated code
+
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
+using scg = global::System.Collections.Generic;
+namespace Grpc.Testing {
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ public static partial class Test {
+
+ #region Descriptor
+ public static pbr::FileDescriptor Descriptor {
+ get { return descriptor; }
+ }
+ private static pbr::FileDescriptor descriptor;
+
+ static Test() {
+ byte[] descriptorData = global::System.Convert.FromBase64String(
+ string.Concat(
+ "Cgp0ZXN0LnByb3RvEgxncnBjLnRlc3RpbmcaC2VtcHR5LnByb3RvGg5tZXNz",
+ "YWdlcy5wcm90bzK7BAoLVGVzdFNlcnZpY2USNQoJRW1wdHlDYWxsEhMuZ3Jw",
+ "Yy50ZXN0aW5nLkVtcHR5GhMuZ3JwYy50ZXN0aW5nLkVtcHR5EkYKCVVuYXJ5",
+ "Q2FsbBIbLmdycGMudGVzdGluZy5TaW1wbGVSZXF1ZXN0GhwuZ3JwYy50ZXN0",
+ "aW5nLlNpbXBsZVJlc3BvbnNlEmwKE1N0cmVhbWluZ091dHB1dENhbGwSKC5n",
+ "cnBjLnRlc3RpbmcuU3RyZWFtaW5nT3V0cHV0Q2FsbFJlcXVlc3QaKS5ncnBj",
+ "LnRlc3RpbmcuU3RyZWFtaW5nT3V0cHV0Q2FsbFJlc3BvbnNlMAESaQoSU3Ry",
+ "ZWFtaW5nSW5wdXRDYWxsEicuZ3JwYy50ZXN0aW5nLlN0cmVhbWluZ0lucHV0",
+ "Q2FsbFJlcXVlc3QaKC5ncnBjLnRlc3RpbmcuU3RyZWFtaW5nSW5wdXRDYWxs",
+ "UmVzcG9uc2UoARJpCg5GdWxsRHVwbGV4Q2FsbBIoLmdycGMudGVzdGluZy5T",
+ "dHJlYW1pbmdPdXRwdXRDYWxsUmVxdWVzdBopLmdycGMudGVzdGluZy5TdHJl",
+ "YW1pbmdPdXRwdXRDYWxsUmVzcG9uc2UoATABEmkKDkhhbGZEdXBsZXhDYWxs",
+ "EiguZ3JwYy50ZXN0aW5nLlN0cmVhbWluZ091dHB1dENhbGxSZXF1ZXN0Giku",
+ "Z3JwYy50ZXN0aW5nLlN0cmVhbWluZ091dHB1dENhbGxSZXNwb25zZSgBMAFi",
+ "BnByb3RvMw=="));
+ descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
+ new pbr::FileDescriptor[] { global::Grpc.Testing.Proto.Empty.Descriptor, global::Grpc.Testing.Messages.Descriptor, },
+ new pbr::GeneratedCodeInfo(null, null));
+ }
+ #endregion
+
+ }
+}
+
+#endregion Designer generated code
diff --git a/src/csharp/Grpc.IntegrationTesting/TestCredentials.cs b/src/csharp/Grpc.IntegrationTesting/TestCredentials.cs
index da0b7fb910..7a48d6e92e 100644
--- a/src/csharp/Grpc.IntegrationTesting/TestCredentials.cs
+++ b/src/csharp/Grpc.IntegrationTesting/TestCredentials.cs
@@ -37,8 +37,6 @@ using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
-using Google.ProtocolBuffers;
-using grpc.testing;
using Grpc.Core;
using Grpc.Core.Utils;
using NUnit.Framework;
diff --git a/src/csharp/Grpc.IntegrationTesting/TestGrpc.cs b/src/csharp/Grpc.IntegrationTesting/TestGrpc.cs
index 697acb53d8..f63e148475 100644
--- a/src/csharp/Grpc.IntegrationTesting/TestGrpc.cs
+++ b/src/csharp/Grpc.IntegrationTesting/TestGrpc.cs
@@ -7,91 +7,97 @@ using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
-namespace grpc.testing {
+namespace Grpc.Testing {
public static class TestService
{
static readonly string __ServiceName = "grpc.testing.TestService";
- static readonly Marshaller<global::grpc.testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.Empty.ParseFrom);
- static readonly Marshaller<global::grpc.testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.SimpleRequest.ParseFrom);
- static readonly Marshaller<global::grpc.testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.SimpleResponse.ParseFrom);
- static readonly Marshaller<global::grpc.testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingOutputCallRequest.ParseFrom);
- static readonly Marshaller<global::grpc.testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingOutputCallResponse.ParseFrom);
- static readonly Marshaller<global::grpc.testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingInputCallRequest.ParseFrom);
- static readonly Marshaller<global::grpc.testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = Marshallers.Create((arg) => arg.ToByteArray(), global::grpc.testing.StreamingInputCallResponse.ParseFrom);
+ static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
+ static readonly Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom);
+ static readonly Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom);
+ static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallRequest.Parser.ParseFrom);
+ static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallResponse.Parser.ParseFrom);
+ static readonly Marshaller<global::Grpc.Testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallRequest.Parser.ParseFrom);
+ static readonly Marshaller<global::Grpc.Testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallResponse.Parser.ParseFrom);
- static readonly Method<global::grpc.testing.Empty, global::grpc.testing.Empty> __Method_EmptyCall = new Method<global::grpc.testing.Empty, global::grpc.testing.Empty>(
+ static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_EmptyCall = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
MethodType.Unary,
__ServiceName,
"EmptyCall",
__Marshaller_Empty,
__Marshaller_Empty);
- static readonly Method<global::grpc.testing.SimpleRequest, global::grpc.testing.SimpleResponse> __Method_UnaryCall = new Method<global::grpc.testing.SimpleRequest, global::grpc.testing.SimpleResponse>(
+ static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
MethodType.Unary,
__ServiceName,
"UnaryCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
- static readonly Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse>(
+ static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.ServerStreaming,
__ServiceName,
"StreamingOutputCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
- static readonly Method<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> __Method_StreamingInputCall = new Method<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse>(
+ static readonly Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> __Method_StreamingInputCall = new Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse>(
MethodType.ClientStreaming,
__ServiceName,
"StreamingInputCall",
__Marshaller_StreamingInputCallRequest,
__Marshaller_StreamingInputCallResponse);
- static readonly Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse>(
+ static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"FullDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
- static readonly Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new Method<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse>(
+ static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"HalfDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
+ // service descriptor
+ public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
+ {
+ get { return global::Grpc.Testing.Test.Descriptor.Services[0]; }
+ }
+
// client interface
public interface ITestServiceClient
{
- global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, CallOptions options);
- AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, CallOptions options);
- global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, CallOptions options);
- AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, CallOptions options);
- AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, CallOptions options);
- AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options);
- AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options);
- AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
- AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options);
+ global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, CallOptions options);
+ AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, CallOptions options);
+ global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options);
+ AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options);
+ AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, CallOptions options);
+ AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options);
+ AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options);
+ AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
+ AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options);
}
// server-side interface
public interface ITestService
{
- Task<global::grpc.testing.Empty> EmptyCall(global::grpc.testing.Empty request, ServerCallContext context);
- Task<global::grpc.testing.SimpleResponse> UnaryCall(global::grpc.testing.SimpleRequest request, ServerCallContext context);
- Task StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, IServerStreamWriter<global::grpc.testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
- Task<global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<global::grpc.testing.StreamingInputCallRequest> requestStream, ServerCallContext context);
- Task FullDuplexCall(IAsyncStreamReader<global::grpc.testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::grpc.testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
- Task HalfDuplexCall(IAsyncStreamReader<global::grpc.testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::grpc.testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
+ Task<global::Grpc.Testing.Empty> EmptyCall(global::Grpc.Testing.Empty request, ServerCallContext context);
+ Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, ServerCallContext context);
+ Task StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
+ Task<global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<global::Grpc.Testing.StreamingInputCallRequest> requestStream, ServerCallContext context);
+ Task FullDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
+ Task HalfDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
}
// client stub
@@ -100,82 +106,82 @@ namespace grpc.testing {
public TestServiceClient(Channel channel) : base(channel)
{
}
- public global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_EmptyCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.BlockingUnaryCall(call, request);
}
- public global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, CallOptions options)
+ public global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, CallOptions options)
{
var call = CreateCall(__Method_EmptyCall, options);
return Calls.BlockingUnaryCall(call, request);
}
- public AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_EmptyCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncUnaryCall(call, request);
}
- public AsyncUnaryCall<global::grpc.testing.Empty> EmptyCallAsync(global::grpc.testing.Empty request, CallOptions options)
+ public AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
var call = CreateCall(__Method_EmptyCall, options);
return Calls.AsyncUnaryCall(call, request);
}
- public global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_UnaryCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.BlockingUnaryCall(call, request);
}
- public global::grpc.testing.SimpleResponse UnaryCall(global::grpc.testing.SimpleRequest request, CallOptions options)
+ public global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options)
{
var call = CreateCall(__Method_UnaryCall, options);
return Calls.BlockingUnaryCall(call, request);
}
- public AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_UnaryCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncUnaryCall(call, request);
}
- public AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, CallOptions options)
+ public AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options)
{
var call = CreateCall(__Method_UnaryCall, options);
return Calls.AsyncUnaryCall(call, request);
}
- public AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_StreamingOutputCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncServerStreamingCall(call, request);
}
- public AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, CallOptions options)
+ public AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, CallOptions options)
{
var call = CreateCall(__Method_StreamingOutputCall, options);
return Calls.AsyncServerStreamingCall(call, request);
}
- public AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_StreamingInputCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncClientStreamingCall(call);
}
- public AsyncClientStreamingCall<global::grpc.testing.StreamingInputCallRequest, global::grpc.testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options)
+ public AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options)
{
var call = CreateCall(__Method_StreamingInputCall, options);
return Calls.AsyncClientStreamingCall(call);
}
- public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_FullDuplexCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncDuplexStreamingCall(call);
}
- public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options)
+ public AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options)
{
var call = CreateCall(__Method_FullDuplexCall, options);
return Calls.AsyncDuplexStreamingCall(call);
}
- public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
+ public AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_HalfDuplexCall, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncDuplexStreamingCall(call);
}
- public AsyncDuplexStreamingCall<global::grpc.testing.StreamingOutputCallRequest, global::grpc.testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options)
+ public AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options)
{
var call = CreateCall(__Method_HalfDuplexCall, options);
return Calls.AsyncDuplexStreamingCall(call);
diff --git a/src/csharp/Grpc.IntegrationTesting/TestServiceImpl.cs b/src/csharp/Grpc.IntegrationTesting/TestServiceImpl.cs
index ceebd5dd8c..c5bfcf08c0 100644
--- a/src/csharp/Grpc.IntegrationTesting/TestServiceImpl.cs
+++ b/src/csharp/Grpc.IntegrationTesting/TestServiceImpl.cs
@@ -35,11 +35,11 @@ using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
-using Google.ProtocolBuffers;
+using Google.Protobuf;
using Grpc.Core;
using Grpc.Core.Utils;
-namespace grpc.testing
+namespace Grpc.Testing
{
/// <summary>
/// Implementation of TestService server
@@ -48,22 +48,20 @@ namespace grpc.testing
{
public Task<Empty> EmptyCall(Empty request, ServerCallContext context)
{
- return Task.FromResult(Empty.DefaultInstance);
+ return Task.FromResult(new Empty());
}
public Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context)
{
- var response = SimpleResponse.CreateBuilder()
- .SetPayload(CreateZerosPayload(request.ResponseSize)).Build();
+ var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) };
return Task.FromResult(response);
}
public async Task StreamingOutputCall(StreamingOutputCallRequest request, IServerStreamWriter<StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
- foreach (var responseParam in request.ResponseParametersList)
+ foreach (var responseParam in request.ResponseParameters)
{
- var response = StreamingOutputCallResponse.CreateBuilder()
- .SetPayload(CreateZerosPayload(responseParam.Size)).Build();
+ var response = new StreamingOutputCallResponse { Payload = CreateZerosPayload(responseParam.Size) };
await responseStream.WriteAsync(response);
}
}
@@ -75,17 +73,16 @@ namespace grpc.testing
{
sum += request.Payload.Body.Length;
});
- return StreamingInputCallResponse.CreateBuilder().SetAggregatedPayloadSize(sum).Build();
+ return new StreamingInputCallResponse { AggregatedPayloadSize = sum };
}
public async Task FullDuplexCall(IAsyncStreamReader<StreamingOutputCallRequest> requestStream, IServerStreamWriter<StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
await requestStream.ForEachAsync(async request =>
{
- foreach (var responseParam in request.ResponseParametersList)
+ foreach (var responseParam in request.ResponseParameters)
{
- var response = StreamingOutputCallResponse.CreateBuilder()
- .SetPayload(CreateZerosPayload(responseParam.Size)).Build();
+ var response = new StreamingOutputCallResponse { Payload = CreateZerosPayload(responseParam.Size) };
await responseStream.WriteAsync(response);
}
});
@@ -98,7 +95,7 @@ namespace grpc.testing
private static Payload CreateZerosPayload(int size)
{
- return Payload.CreateBuilder().SetBody(ByteString.CopyFrom(new byte[size])).Build();
+ return new Payload { Body = ByteString.CopyFrom(new byte[size]) };
}
}
}
diff --git a/src/csharp/Grpc.IntegrationTesting/packages.config b/src/csharp/Grpc.IntegrationTesting/packages.config
index 0867b091b9..8dfded1964 100644
--- a/src/csharp/Grpc.IntegrationTesting/packages.config
+++ b/src/csharp/Grpc.IntegrationTesting/packages.config
@@ -3,6 +3,7 @@
<package id="BouncyCastle" version="1.7.0" targetFramework="net45" />
<package id="Google.Apis.Auth" version="1.9.3" targetFramework="net45" />
<package id="Google.Apis.Core" version="1.9.3" targetFramework="net45" />
+ <package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Google.ProtocolBuffers" version="2.4.1.521" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
<package id="Microsoft.Bcl" version="1.1.10" targetFramework="net45" />
diff --git a/src/csharp/Grpc.IntegrationTesting/proto/empty.proto b/src/csharp/Grpc.IntegrationTesting/proto/empty.proto
index 4295a0a960..6d0eb937d6 100644
--- a/src/csharp/Grpc.IntegrationTesting/proto/empty.proto
+++ b/src/csharp/Grpc.IntegrationTesting/proto/empty.proto
@@ -28,7 +28,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-syntax = "proto2";
+syntax = "proto3";
package grpc.testing;
diff --git a/src/csharp/Grpc.IntegrationTesting/proto/messages.proto b/src/csharp/Grpc.IntegrationTesting/proto/messages.proto
index 65a8140465..7df85e3c13 100644
--- a/src/csharp/Grpc.IntegrationTesting/proto/messages.proto
+++ b/src/csharp/Grpc.IntegrationTesting/proto/messages.proto
@@ -30,7 +30,7 @@
// Message definitions to be used by integration test service definitions.
-syntax = "proto2";
+syntax = "proto3";
package grpc.testing;
@@ -49,46 +49,46 @@ enum PayloadType {
// A block of data, to simply increase gRPC message size.
message Payload {
// The type of data in body.
- optional PayloadType type = 1;
+ PayloadType type = 1;
// Primary contents of payload.
- optional bytes body = 2;
+ bytes body = 2;
}
// Unary request.
message SimpleRequest {
// Desired payload type in the response from the server.
// If response_type is RANDOM, server randomly chooses one from other formats.
- optional PayloadType response_type = 1;
+ PayloadType response_type = 1;
// Desired payload size in the response from the server.
// If response_type is COMPRESSABLE, this denotes the size before compression.
- optional int32 response_size = 2;
+ int32 response_size = 2;
// Optional input payload sent along with the request.
- optional Payload payload = 3;
+ Payload payload = 3;
// Whether SimpleResponse should include username.
- optional bool fill_username = 4;
+ bool fill_username = 4;
// Whether SimpleResponse should include OAuth scope.
- optional bool fill_oauth_scope = 5;
+ bool fill_oauth_scope = 5;
}
// Unary response, as configured by the request.
message SimpleResponse {
// Payload to increase message size.
- optional Payload payload = 1;
+ Payload payload = 1;
// The user the request came from, for verifying authentication was
// successful when the client expected it.
- optional string username = 2;
+ string username = 2;
// OAuth scope.
- optional string oauth_scope = 3;
+ string oauth_scope = 3;
}
// Client-streaming request.
message StreamingInputCallRequest {
// Optional input payload sent along with the request.
- optional Payload payload = 1;
+ Payload payload = 1;
// Not expecting any payload from the response.
}
@@ -96,18 +96,18 @@ message StreamingInputCallRequest {
// Client-streaming response.
message StreamingInputCallResponse {
// Aggregated size of payloads received from the client.
- optional int32 aggregated_payload_size = 1;
+ int32 aggregated_payload_size = 1;
}
// Configuration for a particular response.
message ResponseParameters {
// Desired payload sizes in responses from the server.
// If response_type is COMPRESSABLE, this denotes the size before compression.
- optional int32 size = 1;
+ int32 size = 1;
// Desired interval between consecutive responses in the response stream in
// microseconds.
- optional int32 interval_us = 2;
+ int32 interval_us = 2;
}
// Server-streaming request.
@@ -116,17 +116,17 @@ message StreamingOutputCallRequest {
// If response_type is RANDOM, the payload from each response in the stream
// might be of different types. This is to simulate a mixed type of payload
// stream.
- optional PayloadType response_type = 1;
+ PayloadType response_type = 1;
// Configuration for each expected response message.
repeated ResponseParameters response_parameters = 2;
// Optional input payload sent along with the request.
- optional Payload payload = 3;
+ Payload payload = 3;
}
// Server-streaming response, as configured by the request and parameters.
message StreamingOutputCallResponse {
// Payload to increase response size.
- optional Payload payload = 1;
+ Payload payload = 1;
}
diff --git a/src/csharp/Grpc.IntegrationTesting/proto/test.proto b/src/csharp/Grpc.IntegrationTesting/proto/test.proto
index 927a3a83aa..f9e0d2a039 100644
--- a/src/csharp/Grpc.IntegrationTesting/proto/test.proto
+++ b/src/csharp/Grpc.IntegrationTesting/proto/test.proto
@@ -30,7 +30,7 @@
// An integration test service that covers all the method signature permutations
// of unary/streaming requests/responses.
-syntax = "proto2";
+syntax = "proto3";
import "empty.proto";
import "messages.proto";
diff --git a/src/csharp/Grpc.Tools.nuspec b/src/csharp/Grpc.Tools.nuspec
index eabf5dc7db..48a7b1f3af 100644
--- a/src/csharp/Grpc.Tools.nuspec
+++ b/src/csharp/Grpc.Tools.nuspec
@@ -4,19 +4,18 @@
<id>Grpc.Tools</id>
<title>gRPC C# Tools</title>
<summary>Tools for C# implementation of gRPC - an RPC library and framework</summary>
- <description>Precompiled Windows binaries for generating protocol buffer messages and gRPC client/server code</description>
+ <description>Precompiled Windows binary for generating gRPC client/server code</description>
<version>$version$</version>
<authors>Google Inc.</authors>
<owners>grpc-packages</owners>
<licenseUrl>https://github.com/grpc/grpc/blob/master/LICENSE</licenseUrl>
<projectUrl>https://github.com/grpc/grpc</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
- <releaseNotes>protoc.exe - protocol buffer compiler v3.0.0-alpha-3; grpc_csharp_plugin.exe - gRPC C# protoc plugin version $version$</releaseNotes>
+ <releaseNotes>grpc_csharp_plugin.exe - gRPC C# protoc plugin version $version$</releaseNotes>
<copyright>Copyright 2015, Google Inc.</copyright>
<tags>gRPC RPC Protocol HTTP/2</tags>
</metadata>
<files>
- <file src="protoc.exe" target="tools" />
- <file src="grpc_csharp_plugin.exe" target="tools" />
+ <file src="..\..\vsprojects\Release\grpc_csharp_plugin.exe" target="tools" />
</files>
</package>
diff --git a/src/csharp/README.md b/src/csharp/README.md
index bb5e165986..30523b3bd2 100644
--- a/src/csharp/README.md
+++ b/src/csharp/README.md
@@ -19,7 +19,7 @@ Usage: Windows
That will also pull all the transitive dependencies (including the native libraries that
gRPC C# is internally using).
-- Helloworld project example can be found in https://github.com/grpc/grpc-common/tree/master/csharp.
+- Helloworld project example can be found in https://github.com/grpc/grpc/tree/master/examples/csharp.
Usage: Linux (Mono)
--------------
@@ -50,7 +50,7 @@ Usage: Linux (Mono)
- Add NuGet package `Grpc` as a dependency (Project -> Add NuGet packages).
-- Helloworld project example can be found in https://github.com/grpc/grpc-common/tree/master/csharp.
+- Helloworld project example can be found in https://github.com/grpc/grpc/tree/master/examples/csharp.
Usage: MacOS (Mono)
--------------
@@ -73,7 +73,7 @@ Usage: MacOS (Mono)
- *You will be able to build your project in Xamarin Studio, but to run or test it,
you will need to run it under 64-bit version of Mono.*
-- Helloworld project example can be found in https://github.com/grpc/grpc-common/tree/master/csharp.
+- Helloworld project example can be found in https://github.com/grpc/grpc/tree/master/examples/csharp.
Building: Windows
-----------------
diff --git a/src/csharp/build_packages.bat b/src/csharp/build_packages.bat
index 8a11d01430..255b7469ab 100644
--- a/src/csharp/build_packages.bat
+++ b/src/csharp/build_packages.bat
@@ -1,8 +1,9 @@
@rem Builds gRPC NuGet packages
@rem Current package versions
-set VERSION=0.6.1
-set CORE_VERSION=0.10.1
+set VERSION=0.7.0
+set CORE_VERSION=0.11.0
+set PROTOBUF_VERSION=3.0.0-alpha4
@rem Adjust the location of nuget.exe
set NUGET=C:\nuget\nuget.exe
@@ -14,10 +15,12 @@ endlocal
@call buildall.bat BUILD_SIGNED || goto :error
+@call ..\..\vsprojects\build_plugins.bat || goto :error
+
%NUGET% pack ..\..\vsprojects\nuget_package\grpc.native.csharp_ext.nuspec -Version %CORE_VERSION% || goto :error
%NUGET% pack Grpc.Auth\Grpc.Auth.nuspec -Symbols -Version %VERSION% || goto :error
%NUGET% pack Grpc.Core\Grpc.Core.nuspec -Symbols -Version %VERSION% -Properties GrpcNativeCsharpExtVersion=%CORE_VERSION% || goto :error
-%NUGET% pack Grpc.HealthCheck\Grpc.HealthCheck.nuspec -Symbols -Version %VERSION% || goto :error
+%NUGET% pack Grpc.HealthCheck\Grpc.HealthCheck.nuspec -Symbols -Version %VERSION% -Properties ProtobufVersion=%PROTOBUF_VERSION% || goto :error
%NUGET% pack Grpc.Tools.nuspec -Version %VERSION% || goto :error
%NUGET% pack Grpc.nuspec -Version %VERSION% || goto :error
diff --git a/src/csharp/ext/grpc_csharp_ext.c b/src/csharp/ext/grpc_csharp_ext.c
index 489e219c49..70c0fbcc50 100644
--- a/src/csharp/ext/grpc_csharp_ext.c
+++ b/src/csharp/ext/grpc_csharp_ext.c
@@ -837,11 +837,11 @@ grpcsharp_ssl_credentials_create(const char *pem_root_certs,
if (key_cert_pair_cert_chain || key_cert_pair_private_key) {
key_cert_pair.cert_chain = key_cert_pair_cert_chain;
key_cert_pair.private_key = key_cert_pair_private_key;
- return grpc_ssl_credentials_create(pem_root_certs, &key_cert_pair);
+ return grpc_ssl_credentials_create(pem_root_certs, &key_cert_pair, NULL);
} else {
GPR_ASSERT(!key_cert_pair_cert_chain);
GPR_ASSERT(!key_cert_pair_private_key);
- return grpc_ssl_credentials_create(pem_root_certs, NULL);
+ return grpc_ssl_credentials_create(pem_root_certs, NULL, NULL);
}
}
@@ -852,7 +852,7 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_credentials_release(grpc_credentials *cre
GPR_EXPORT grpc_channel *GPR_CALLTYPE
grpcsharp_secure_channel_create(grpc_credentials *creds, const char *target,
const grpc_channel_args *args) {
- return grpc_secure_channel_create(creds, target, args);
+ return grpc_secure_channel_create(creds, target, args, NULL);
}
GPR_EXPORT grpc_server_credentials *GPR_CALLTYPE
@@ -876,7 +876,7 @@ grpcsharp_ssl_server_credentials_create(
}
creds = grpc_ssl_server_credentials_create(pem_root_certs, key_cert_pairs,
num_key_cert_pairs,
- force_client_auth);
+ force_client_auth, NULL);
gpr_free(key_cert_pairs);
return creds;
}
diff --git a/src/csharp/generate_proto_csharp.sh b/src/csharp/generate_proto_csharp.sh
index 7c3ba70922..a17f45b587 100755
--- a/src/csharp/generate_proto_csharp.sh
+++ b/src/csharp/generate_proto_csharp.sh
@@ -38,11 +38,11 @@ EXAMPLES_DIR=Grpc.Examples
INTEROP_DIR=Grpc.IntegrationTesting
HEALTHCHECK_DIR=Grpc.HealthCheck
-$PROTOC --plugin=$PLUGIN --grpc_out=$EXAMPLES_DIR \
+$PROTOC --plugin=$PLUGIN --csharp_out=$EXAMPLES_DIR --grpc_out=$EXAMPLES_DIR \
-I $EXAMPLES_DIR/proto $EXAMPLES_DIR/proto/math.proto
-$PROTOC --plugin=$PLUGIN --grpc_out=$INTEROP_DIR \
- -I $INTEROP_DIR/proto $INTEROP_DIR/proto/test.proto
+$PROTOC --plugin=$PLUGIN --csharp_out=$INTEROP_DIR --grpc_out=$INTEROP_DIR \
+ -I $INTEROP_DIR/proto $INTEROP_DIR/proto/*.proto
-$PROTOC --plugin=$PLUGIN --grpc_out=$HEALTHCHECK_DIR \
+$PROTOC --plugin=$PLUGIN --csharp_out=$HEALTHCHECK_DIR --grpc_out=$HEALTHCHECK_DIR \
-I $HEALTHCHECK_DIR/proto $HEALTHCHECK_DIR/proto/health.proto
diff --git a/src/node/ext/call.cc b/src/node/ext/call.cc
index 18858fa334..fddc1e214f 100644
--- a/src/node/ext/call.cc
+++ b/src/node/ext/call.cc
@@ -111,17 +111,19 @@ bool CreateMetadataArray(Handle<Object> metadata, grpc_metadata_array *array,
NanAssignPersistent(*handle, value);
resources->handles.push_back(unique_ptr<PersistentHolder>(
new PersistentHolder(handle)));
- continue;
+ } else {
+ return false;
}
- }
- if (value->IsString()) {
- Handle<String> string_value = value->ToString();
- NanUtf8String *utf8_value = new NanUtf8String(string_value);
- resources->strings.push_back(unique_ptr<NanUtf8String>(utf8_value));
- current->value = **utf8_value;
- current->value_length = string_value->Length();
} else {
- return false;
+ if (value->IsString()) {
+ Handle<String> string_value = value->ToString();
+ NanUtf8String *utf8_value = new NanUtf8String(string_value);
+ resources->strings.push_back(unique_ptr<NanUtf8String>(utf8_value));
+ current->value = **utf8_value;
+ current->value_length = string_value->Length();
+ } else {
+ return false;
+ }
}
array->count += 1;
}
@@ -156,8 +158,7 @@ Handle<Value> ParseMetadata(const grpc_metadata_array *metadata_array) {
}
if (EndsWith(elem->key, "-bin")) {
array->Set(index_map[elem->key],
- MakeFastBuffer(
- NanNewBufferHandle(elem->value, elem->value_length)));
+ NanNewBufferHandle(elem->value, elem->value_length));
} else {
array->Set(index_map[elem->key], NanNew(elem->value));
}
diff --git a/src/node/ext/channel.cc b/src/node/ext/channel.cc
index a61c830099..9aed96bbf5 100644
--- a/src/node/ext/channel.cc
+++ b/src/node/ext/channel.cc
@@ -161,7 +161,7 @@ NAN_METHOD(Channel::New) {
NULL);
} else {
wrapped_channel =
- grpc_secure_channel_create(creds, *host, channel_args_ptr);
+ grpc_secure_channel_create(creds, *host, channel_args_ptr, NULL);
}
if (channel_args_ptr != NULL) {
free(channel_args_ptr->args);
diff --git a/src/node/ext/credentials.cc b/src/node/ext/credentials.cc
index 21d61f1a7f..85a823a108 100644
--- a/src/node/ext/credentials.cc
+++ b/src/node/ext/credentials.cc
@@ -156,7 +156,8 @@ NAN_METHOD(Credentials::CreateSsl) {
"createSSl's third argument must be a Buffer if provided");
}
grpc_credentials *creds = grpc_ssl_credentials_create(
- root_certs, key_cert_pair.private_key == NULL ? NULL : &key_cert_pair);
+ root_certs, key_cert_pair.private_key == NULL ? NULL : &key_cert_pair,
+ NULL);
if (creds == NULL) {
NanReturnNull();
}
@@ -176,7 +177,7 @@ NAN_METHOD(Credentials::CreateComposite) {
Credentials *creds1 = ObjectWrap::Unwrap<Credentials>(args[0]->ToObject());
Credentials *creds2 = ObjectWrap::Unwrap<Credentials>(args[1]->ToObject());
grpc_credentials *creds = grpc_composite_credentials_create(
- creds1->wrapped_credentials, creds2->wrapped_credentials);
+ creds1->wrapped_credentials, creds2->wrapped_credentials, NULL);
if (creds == NULL) {
NanReturnNull();
}
@@ -185,7 +186,7 @@ NAN_METHOD(Credentials::CreateComposite) {
NAN_METHOD(Credentials::CreateGce) {
NanScope();
- grpc_credentials *creds = grpc_compute_engine_credentials_create();
+ grpc_credentials *creds = grpc_compute_engine_credentials_create(NULL);
if (creds == NULL) {
NanReturnNull();
}
@@ -202,8 +203,8 @@ NAN_METHOD(Credentials::CreateIam) {
}
NanUtf8String auth_token(args[0]);
NanUtf8String auth_selector(args[1]);
- grpc_credentials *creds = grpc_iam_credentials_create(*auth_token,
- *auth_selector);
+ grpc_credentials *creds =
+ grpc_iam_credentials_create(*auth_token, *auth_selector, NULL);
if (creds == NULL) {
NanReturnNull();
}
diff --git a/src/node/ext/server.cc b/src/node/ext/server.cc
index 01217bce79..32a8ff55b1 100644
--- a/src/node/ext/server.cc
+++ b/src/node/ext/server.cc
@@ -120,7 +120,7 @@ Server::Server(grpc_server *server) : wrapped_server(server) {
Server::~Server() {
this->ShutdownServer();
grpc_completion_queue_shutdown(this->shutdown_queue);
- grpc_server_destroy(wrapped_server);
+ grpc_server_destroy(this->wrapped_server);
grpc_completion_queue_destroy(this->shutdown_queue);
}
@@ -139,8 +139,11 @@ void Server::Init(Handle<Object> exports) {
NanSetPrototypeTemplate(tpl, "start",
NanNew<FunctionTemplate>(Start)->GetFunction());
- NanSetPrototypeTemplate(tpl, "shutdown",
- NanNew<FunctionTemplate>(Shutdown)->GetFunction());
+ NanSetPrototypeTemplate(tpl, "tryShutdown",
+ NanNew<FunctionTemplate>(TryShutdown)->GetFunction());
+ NanSetPrototypeTemplate(
+ tpl, "forceShutdown",
+ NanNew<FunctionTemplate>(ForceShutdown)->GetFunction());
NanAssignPersistent(fun_tpl, tpl);
Handle<Function> ctr = tpl->GetFunction();
@@ -153,14 +156,12 @@ bool Server::HasInstance(Handle<Value> val) {
}
void Server::ShutdownServer() {
- if (this->wrapped_server != NULL) {
- grpc_server_shutdown_and_notify(this->wrapped_server,
- this->shutdown_queue,
- NULL);
- grpc_completion_queue_pluck(this->shutdown_queue, NULL,
- gpr_inf_future(GPR_CLOCK_REALTIME), NULL);
- this->wrapped_server = NULL;
- }
+ grpc_server_shutdown_and_notify(this->wrapped_server,
+ this->shutdown_queue,
+ NULL);
+ grpc_server_cancel_all_calls(this->wrapped_server);
+ grpc_completion_queue_pluck(this->shutdown_queue, NULL,
+ gpr_inf_future(GPR_CLOCK_REALTIME), NULL);
}
NAN_METHOD(Server::New) {
@@ -222,9 +223,6 @@ NAN_METHOD(Server::RequestCall) {
return NanThrowTypeError("requestCall can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
- if (server->wrapped_server == NULL) {
- return NanThrowError("requestCall cannot be called on a shut down Server");
- }
NewCallOp *op = new NewCallOp();
unique_ptr<OpVec> ops(new OpVec());
ops->push_back(unique_ptr<Op>(op));
@@ -256,10 +254,6 @@ NAN_METHOD(Server::AddHttp2Port) {
"addHttp2Port's second argument must be ServerCredentials");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
- if (server->wrapped_server == NULL) {
- return NanThrowError(
- "addHttp2Port cannot be called on a shut down Server");
- }
ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(
args[1]->ToObject());
grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();
@@ -281,21 +275,30 @@ NAN_METHOD(Server::Start) {
return NanThrowTypeError("start can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
- if (server->wrapped_server == NULL) {
- return NanThrowError("start cannot be called on a shut down Server");
- }
grpc_server_start(server->wrapped_server);
NanReturnUndefined();
}
-NAN_METHOD(ShutdownCallback) {
+NAN_METHOD(Server::TryShutdown) {
+ NanScope();
+ if (!HasInstance(args.This())) {
+ return NanThrowTypeError("tryShutdown can only be called on a Server");
+ }
+ Server *server = ObjectWrap::Unwrap<Server>(args.This());
+ unique_ptr<OpVec> ops(new OpVec());
+ grpc_server_shutdown_and_notify(
+ server->wrapped_server,
+ CompletionQueueAsyncWorker::GetQueue(),
+ new struct tag(new NanCallback(args[0].As<Function>()), ops.release(),
+ shared_ptr<Resources>(nullptr)));
+ CompletionQueueAsyncWorker::Next();
NanReturnUndefined();
}
-NAN_METHOD(Server::Shutdown) {
+NAN_METHOD(Server::ForceShutdown) {
NanScope();
if (!HasInstance(args.This())) {
- return NanThrowTypeError("shutdown can only be called on a Server");
+ return NanThrowTypeError("forceShutdown can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
server->ShutdownServer();
diff --git a/src/node/ext/server.h b/src/node/ext/server.h
index faab7e3418..e7d5c3fb11 100644
--- a/src/node/ext/server.h
+++ b/src/node/ext/server.h
@@ -67,7 +67,8 @@ class Server : public ::node::ObjectWrap {
static NAN_METHOD(RequestCall);
static NAN_METHOD(AddHttp2Port);
static NAN_METHOD(Start);
- static NAN_METHOD(Shutdown);
+ static NAN_METHOD(TryShutdown);
+ static NAN_METHOD(ForceShutdown);
static NanCallback *constructor;
static v8::Persistent<v8::FunctionTemplate> fun_tpl;
diff --git a/src/node/ext/server_credentials.cc b/src/node/ext/server_credentials.cc
index 6e17197e16..b1201eb664 100644
--- a/src/node/ext/server_credentials.cc
+++ b/src/node/ext/server_credentials.cc
@@ -178,11 +178,8 @@ NAN_METHOD(ServerCredentials::CreateSsl) {
key_cert_pairs[i].cert_chain = ::node::Buffer::Data(
pair_obj->Get(cert_key));
}
- grpc_server_credentials *creds =
- grpc_ssl_server_credentials_create(root_certs,
- key_cert_pairs,
- key_cert_pair_count,
- force_client_auth);
+ grpc_server_credentials *creds = grpc_ssl_server_credentials_create(
+ root_certs, key_cert_pairs, key_cert_pair_count, force_client_auth, NULL);
delete key_cert_pairs;
if (creds == NULL) {
NanReturnNull();
diff --git a/src/node/index.js b/src/node/index.js
index 889b0ac0e9..51d3fa590c 100644
--- a/src/node/index.js
+++ b/src/node/index.js
@@ -41,6 +41,8 @@ var client = require('./src/client.js');
var server = require('./src/server.js');
+var Metadata = require('./src/metadata.js');
+
var grpc = require('bindings')('grpc');
/**
@@ -107,18 +109,12 @@ exports.getGoogleAuthDelegate = function getGoogleAuthDelegate(credential) {
* @param {function(Error, Object)} callback
*/
return function updateMetadata(authURI, metadata, callback) {
- metadata = _.clone(metadata);
- if (metadata.Authorization) {
- metadata.Authorization = _.clone(metadata.Authorization);
- } else {
- metadata.Authorization = [];
- }
credential.getRequestMetadata(authURI, function(err, header) {
if (err) {
callback(err);
return;
}
- metadata.Authorization.push(header.Authorization);
+ metadata.add('authorization', header.Authorization);
callback(null, metadata);
});
};
@@ -130,6 +126,11 @@ exports.getGoogleAuthDelegate = function getGoogleAuthDelegate(credential) {
exports.Server = server.Server;
/**
+ * @see module:src/metadata
+ */
+exports.Metadata = Metadata;
+
+/**
* Status name to code number mapping
*/
exports.status = grpc.status;
diff --git a/src/node/interop/interop_client.js b/src/node/interop/interop_client.js
index 612dcf01f6..8fb8d66920 100644
--- a/src/node/interop/interop_client.js
+++ b/src/node/interop/interop_client.js
@@ -321,13 +321,7 @@ function oauth2Test(expected_user, scope, per_rpc, client, done) {
credential.getAccessToken(function(err, token) {
assert.ifError(err);
var updateMetadata = function(authURI, metadata, callback) {
- metadata = _.clone(metadata);
- if (metadata.Authorization) {
- metadata.Authorization = _.clone(metadata.Authorization);
- } else {
- metadata.Authorization = [];
- }
- metadata.Authorization.push('Bearer ' + token);
+ metadata.Add('authorization', 'Bearer ' + token);
callback(null, metadata);
};
var makeTestCall = function(error, client_metadata) {
diff --git a/src/node/src/client.js b/src/node/src/client.js
index 7b7eae51d2..e1bed3512e 100644
--- a/src/node/src/client.js
+++ b/src/node/src/client.js
@@ -42,7 +42,9 @@ var _ = require('lodash');
var grpc = require('bindings')('grpc.node');
-var common = require('./common.js');
+var common = require('./common');
+
+var Metadata = require('./metadata');
var EventEmitter = require('events').EventEmitter;
@@ -254,8 +256,7 @@ function makeUnaryRequestFunction(method, serialize, deserialize) {
* serialize
* @param {function(?Error, value=)} callback The callback to for when the
* response is received
- * @param {array=} metadata Array of metadata key/value pairs to add to the
- * call
+ * @param {Metadata=} metadata Metadata to add to the call
* @param {Object=} options Options map
* @return {EventEmitter} An event emitter for stream related events
*/
@@ -264,7 +265,9 @@ function makeUnaryRequestFunction(method, serialize, deserialize) {
var emitter = new EventEmitter();
var call = getCall(this.channel, method, options);
if (metadata === null || metadata === undefined) {
- metadata = {};
+ metadata = new Metadata();
+ } else {
+ metadata = metadata.clone();
}
emitter.cancel = function cancel() {
call.cancel();
@@ -283,13 +286,16 @@ function makeUnaryRequestFunction(method, serialize, deserialize) {
if (options) {
message.grpcWriteFlags = options.flags;
}
- client_batch[grpc.opType.SEND_INITIAL_METADATA] = metadata;
+ client_batch[grpc.opType.SEND_INITIAL_METADATA] =
+ metadata._getCoreRepresentation();
client_batch[grpc.opType.SEND_MESSAGE] = message;
client_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
client_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
client_batch[grpc.opType.RECV_MESSAGE] = true;
client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
call.startBatch(client_batch, function(err, response) {
+ response.status.metadata = Metadata._fromCoreRepresentation(
+ response.status.metadata);
emitter.emit('status', response.status);
if (response.status.code !== grpc.status.OK) {
var error = new Error(response.status.details);
@@ -304,7 +310,8 @@ function makeUnaryRequestFunction(method, serialize, deserialize) {
return;
}
}
- emitter.emit('metadata', response.metadata);
+ emitter.emit('metadata', Metadata._fromCoreRepresentation(
+ response.metadata));
callback(null, deserialize(response.read));
});
});
@@ -328,7 +335,7 @@ function makeClientStreamRequestFunction(method, serialize, deserialize) {
* @this {Client} Client object. Must have a channel member.
* @param {function(?Error, value=)} callback The callback to for when the
* response is received
- * @param {array=} metadata Array of metadata key/value pairs to add to the
+ * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
* call
* @param {Object=} options Options map
* @return {EventEmitter} An event emitter for stream related events
@@ -337,7 +344,9 @@ function makeClientStreamRequestFunction(method, serialize, deserialize) {
/* jshint validthis: true */
var call = getCall(this.channel, method, options);
if (metadata === null || metadata === undefined) {
- metadata = {};
+ metadata = new Metadata();
+ } else {
+ metadata = metadata.clone();
}
var stream = new ClientWritableStream(call, serialize);
this.updateMetadata(this.auth_uri, metadata, function(error, metadata) {
@@ -347,7 +356,8 @@ function makeClientStreamRequestFunction(method, serialize, deserialize) {
return;
}
var metadata_batch = {};
- metadata_batch[grpc.opType.SEND_INITIAL_METADATA] = metadata;
+ metadata_batch[grpc.opType.SEND_INITIAL_METADATA] =
+ metadata._getCoreRepresentation();
metadata_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
call.startBatch(metadata_batch, function(err, response) {
if (err) {
@@ -355,12 +365,15 @@ function makeClientStreamRequestFunction(method, serialize, deserialize) {
// in the other batch.
return;
}
- stream.emit('metadata', response.metadata);
+ stream.emit('metadata', Metadata._fromCoreRepresentation(
+ response.metadata));
});
var client_batch = {};
client_batch[grpc.opType.RECV_MESSAGE] = true;
client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
call.startBatch(client_batch, function(err, response) {
+ response.status.metadata = Metadata._fromCoreRepresentation(
+ response.status.metadata);
stream.emit('status', response.status);
if (response.status.code !== grpc.status.OK) {
var error = new Error(response.status.details);
@@ -398,7 +411,7 @@ function makeServerStreamRequestFunction(method, serialize, deserialize) {
* @this {SurfaceClient} Client object. Must have a channel member.
* @param {*} argument The argument to the call. Should be serializable with
* serialize
- * @param {array=} metadata Array of metadata key/value pairs to add to the
+ * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
* call
* @param {Object} options Options map
* @return {EventEmitter} An event emitter for stream related events
@@ -407,7 +420,9 @@ function makeServerStreamRequestFunction(method, serialize, deserialize) {
/* jshint validthis: true */
var call = getCall(this.channel, method, options);
if (metadata === null || metadata === undefined) {
- metadata = {};
+ metadata = new Metadata();
+ } else {
+ metadata = metadata.clone();
}
var stream = new ClientReadableStream(call, deserialize);
this.updateMetadata(this.auth_uri, metadata, function(error, metadata) {
@@ -421,7 +436,8 @@ function makeServerStreamRequestFunction(method, serialize, deserialize) {
if (options) {
message.grpcWriteFlags = options.flags;
}
- start_batch[grpc.opType.SEND_INITIAL_METADATA] = metadata;
+ start_batch[grpc.opType.SEND_INITIAL_METADATA] =
+ metadata._getCoreRepresentation();
start_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
start_batch[grpc.opType.SEND_MESSAGE] = message;
start_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
@@ -431,11 +447,14 @@ function makeServerStreamRequestFunction(method, serialize, deserialize) {
// in the other batch.
return;
}
- stream.emit('metadata', response.metadata);
+ stream.emit('metadata', Metadata._fromCoreRepresentation(
+ response.metadata));
});
var status_batch = {};
status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
call.startBatch(status_batch, function(err, response) {
+ response.status.metadata = Metadata._fromCoreRepresentation(
+ response.status.metadata);
stream.emit('status', response.status);
if (response.status.code !== grpc.status.OK) {
var error = new Error(response.status.details);
@@ -470,7 +489,7 @@ function makeBidiStreamRequestFunction(method, serialize, deserialize) {
/**
* Make a bidirectional stream request with this method on the given channel.
* @this {SurfaceClient} Client object. Must have a channel member.
- * @param {array=} metadata Array of metadata key/value pairs to add to the
+ * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
* call
* @param {Options} options Options map
* @return {EventEmitter} An event emitter for stream related events
@@ -479,7 +498,9 @@ function makeBidiStreamRequestFunction(method, serialize, deserialize) {
/* jshint validthis: true */
var call = getCall(this.channel, method, options);
if (metadata === null || metadata === undefined) {
- metadata = {};
+ metadata = new Metadata();
+ } else {
+ metadata = metadata.clone();
}
var stream = new ClientDuplexStream(call, serialize, deserialize);
this.updateMetadata(this.auth_uri, metadata, function(error, metadata) {
@@ -489,7 +510,8 @@ function makeBidiStreamRequestFunction(method, serialize, deserialize) {
return;
}
var start_batch = {};
- start_batch[grpc.opType.SEND_INITIAL_METADATA] = metadata;
+ start_batch[grpc.opType.SEND_INITIAL_METADATA] =
+ metadata._getCoreRepresentation();
start_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
call.startBatch(start_batch, function(err, response) {
if (err) {
@@ -497,11 +519,14 @@ function makeBidiStreamRequestFunction(method, serialize, deserialize) {
// in the other batch.
return;
}
- stream.emit('metadata', response.metadata);
+ stream.emit('metadata', Metadata._fromCoreRepresentation(
+ response.metadata));
});
var status_batch = {};
status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
call.startBatch(status_batch, function(err, response) {
+ response.status.metadata = Metadata._fromCoreRepresentation(
+ response.status.metadata);
stream.emit('status', response.status);
if (response.status.code !== grpc.status.OK) {
var error = new Error(response.status.details);
diff --git a/src/node/src/metadata.js b/src/node/src/metadata.js
new file mode 100644
index 0000000000..c1da70b197
--- /dev/null
+++ b/src/node/src/metadata.js
@@ -0,0 +1,181 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * Metadata module
+ * @module
+ */
+
+'use strict';
+
+var _ = require('lodash');
+
+/**
+ * Class for storing metadata. Keys are normalized to lowercase ASCII.
+ * @constructor
+ */
+function Metadata() {
+ this._internal_repr = {};
+}
+
+function normalizeKey(key) {
+ if (!(/^[A-Za-z\d_-]+$/.test(key))) {
+ throw new Error('Metadata keys must be nonempty strings containing only ' +
+ 'alphanumeric characters and hyphens');
+ }
+ return key.toLowerCase();
+}
+
+function validate(key, value) {
+ if (_.endsWith(key, '-bin')) {
+ if (!(value instanceof Buffer)) {
+ throw new Error('keys that end with \'-bin\' must have Buffer values');
+ }
+ } else {
+ if (!_.isString(value)) {
+ throw new Error(
+ 'keys that don\'t end with \'-bin\' must have String values');
+ }
+ if (!(/^[\x20-\x7E]*$/.test(value))) {
+ throw new Error('Metadata string values can only contain printable ' +
+ 'ASCII characters and space');
+ }
+ }
+}
+
+/**
+ * Sets the given value for the given key, replacing any other values associated
+ * with that key. Normalizes the key.
+ * @param {String} key The key to set
+ * @param {String|Buffer} value The value to set. Must be a buffer if and only
+ * if the normalized key ends with '-bin'
+ */
+Metadata.prototype.set = function(key, value) {
+ key = normalizeKey(key);
+ validate(key, value);
+ this._internal_repr[key] = [value];
+};
+
+/**
+ * Adds the given value for the given key. Normalizes the key.
+ * @param {String} key The key to add to.
+ * @param {String|Buffer} value The value to add. Must be a buffer if and only
+ * if the normalized key ends with '-bin'
+ */
+Metadata.prototype.add = function(key, value) {
+ key = normalizeKey(key);
+ validate(key, value);
+ if (!this._internal_repr[key]) {
+ this._internal_repr[key] = [];
+ }
+ this._internal_repr[key].push(value);
+};
+
+/**
+ * Remove the given key and any associated values. Normalizes the key.
+ * @param {String} key The key to remove
+ */
+Metadata.prototype.remove = function(key) {
+ key = normalizeKey(key);
+ if (Object.prototype.hasOwnProperty.call(this._internal_repr, key)) {
+ delete this._internal_repr[key];
+ }
+};
+
+/**
+ * Gets a list of all values associated with the key. Normalizes the key.
+ * @param {String} key The key to get
+ * @return {Array.<String|Buffer>} The values associated with that key
+ */
+Metadata.prototype.get = function(key) {
+ key = normalizeKey(key);
+ if (Object.prototype.hasOwnProperty.call(this._internal_repr, key)) {
+ return this._internal_repr[key];
+ } else {
+ return [];
+ }
+};
+
+/**
+ * Get a map of each key to a single associated value. This reflects the most
+ * common way that people will want to see metadata.
+ * @return {Object.<String,String|Buffer>} A key/value mapping of the metadata
+ */
+Metadata.prototype.getMap = function() {
+ var result = {};
+ _.forOwn(this._internal_repr, function(values, key) {
+ if(values.length > 0) {
+ result[key] = values[0];
+ }
+ });
+ return result;
+};
+
+/**
+ * Clone the metadata object.
+ * @return {Metadata} The new cloned object
+ */
+Metadata.prototype.clone = function() {
+ var copy = new Metadata();
+ _.forOwn(this._internal_repr, function(value, key) {
+ copy._internal_repr[key] = _.clone(value);
+ });
+ return copy;
+};
+
+/**
+ * Gets the metadata in the format used by interal code. Intended for internal
+ * use only. API stability is not guaranteed.
+ * @private
+ * @return {Object.<String, Array.<String|Buffer>>} The metadata
+ */
+Metadata.prototype._getCoreRepresentation = function() {
+ return this._internal_repr;
+};
+
+/**
+ * Creates a Metadata object from a metadata map in the internal format.
+ * Intended for internal use only. API stability is not guaranteed.
+ * @private
+ * @param {Object.<String, Array.<String|Buffer>>} The metadata
+ * @return {Metadata} The new Metadata object
+ */
+Metadata._fromCoreRepresentation = function(metadata) {
+ var newMetadata = new Metadata();
+ if (metadata) {
+ newMetadata._internal_repr = _.cloneDeep(metadata);
+ }
+ return newMetadata;
+};
+
+module.exports = Metadata;
diff --git a/src/node/src/server.js b/src/node/src/server.js
index 5037abae43..b6f162adf8 100644
--- a/src/node/src/server.js
+++ b/src/node/src/server.js
@@ -44,6 +44,8 @@ var grpc = require('bindings')('grpc.node');
var common = require('./common');
+var Metadata = require('./metadata');
+
var stream = require('stream');
var Readable = stream.Readable;
@@ -60,10 +62,10 @@ var EventEmitter = require('events').EventEmitter;
* @param {Object} error The error object
*/
function handleError(call, error) {
+ var statusMetadata = new Metadata();
var status = {
code: grpc.status.UNKNOWN,
- details: 'Unknown Error',
- metadata: {}
+ details: 'Unknown Error'
};
if (error.hasOwnProperty('message')) {
status.details = error.message;
@@ -75,11 +77,13 @@ function handleError(call, error) {
}
}
if (error.hasOwnProperty('metadata')) {
- status.metadata = error.metadata;
+ statusMetadata = error.metadata;
}
+ status.metadata = statusMetadata._getCoreRepresentation();
var error_batch = {};
if (!call.metadataSent) {
- error_batch[grpc.opType.SEND_INITIAL_METADATA] = {};
+ error_batch[grpc.opType.SEND_INITIAL_METADATA] =
+ (new Metadata())._getCoreRepresentation();
}
error_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = status;
call.startBatch(error_batch, function(){});
@@ -114,22 +118,24 @@ function waitForCancel(call, emitter) {
* @param {*} value The value to respond with
* @param {function(*):Buffer=} serialize Serialization function for the
* response
- * @param {Object=} metadata Optional trailing metadata to send with status
+ * @param {Metadata=} metadata Optional trailing metadata to send with status
* @param {number=} flags Flags for modifying how the message is sent.
* Defaults to 0.
*/
function sendUnaryResponse(call, value, serialize, metadata, flags) {
var end_batch = {};
+ var statusMetadata = new Metadata();
var status = {
code: grpc.status.OK,
- details: 'OK',
- metadata: {}
+ details: 'OK'
};
if (metadata) {
- status.metadata = metadata;
+ statusMetadata = metadata;
}
+ status.metadata = statusMetadata._getCoreRepresentation();
if (!call.metadataSent) {
- end_batch[grpc.opType.SEND_INITIAL_METADATA] = {};
+ end_batch[grpc.opType.SEND_INITIAL_METADATA] =
+ (new Metadata())._getCoreRepresentation();
call.metadataSent = true;
}
var message = serialize(value);
@@ -151,14 +157,19 @@ function setUpWritable(stream, serialize) {
stream.status = {
code : grpc.status.OK,
details : 'OK',
- metadata : {}
+ metadata : new Metadata()
};
stream.serialize = common.wrapIgnoreNull(serialize);
function sendStatus() {
var batch = {};
if (!stream.call.metadataSent) {
stream.call.metadataSent = true;
- batch[grpc.opType.SEND_INITIAL_METADATA] = {};
+ batch[grpc.opType.SEND_INITIAL_METADATA] =
+ (new Metadata())._getCoreRepresentation();
+ }
+
+ if (stream.status.metadata) {
+ stream.status.metadata = stream.status.metadata._getCoreRepresentation();
}
batch[grpc.opType.SEND_STATUS_FROM_SERVER] = stream.status;
stream.call.startBatch(batch, function(){});
@@ -173,7 +184,7 @@ function setUpWritable(stream, serialize) {
function setStatus(err) {
var code = grpc.status.UNKNOWN;
var details = 'Unknown Error';
- var metadata = {};
+ var metadata = new Metadata();
if (err.hasOwnProperty('message')) {
details = err.message;
}
@@ -203,7 +214,7 @@ function setUpWritable(stream, serialize) {
/**
* Override of Writable#end method that allows for sending metadata with a
* success status.
- * @param {Object=} metadata Metadata to send with the status
+ * @param {Metadata=} metadata Metadata to send with the status
*/
stream.end = function(metadata) {
if (metadata) {
@@ -266,7 +277,8 @@ function _write(chunk, encoding, callback) {
/* jshint validthis: true */
var batch = {};
if (!this.call.metadataSent) {
- batch[grpc.opType.SEND_INITIAL_METADATA] = {};
+ batch[grpc.opType.SEND_INITIAL_METADATA] =
+ (new Metadata())._getCoreRepresentation();
this.call.metadataSent = true;
}
var message = this.serialize(chunk);
@@ -289,15 +301,15 @@ ServerWritableStream.prototype._write = _write;
/**
* Send the initial metadata for a writable stream.
- * @param {Object<String, Array<(String|Buffer)>>} responseMetadata Metadata
- * to send
+ * @param {Metadata} responseMetadata Metadata to send
*/
function sendMetadata(responseMetadata) {
/* jshint validthis: true */
if (!this.call.metadataSent) {
this.call.metadataSent = true;
var batch = [];
- batch[grpc.opType.SEND_INITIAL_METADATA] = responseMetadata;
+ batch[grpc.opType.SEND_INITIAL_METADATA] =
+ responseMetadata._getCoreRepresentation();
this.call.startBatch(batch, function(err) {
if (err) {
this.emit('error', err);
@@ -422,7 +434,7 @@ ServerDuplexStream.prototype.getPeer = getPeer;
* @access private
* @param {grpc.Call} call The call to handle
* @param {Object} handler Request handler object for the method that was called
- * @param {Object} metadata Metadata from the client
+ * @param {Metadata} metadata Metadata from the client
*/
function handleUnary(call, handler, metadata) {
var emitter = new EventEmitter();
@@ -430,7 +442,8 @@ function handleUnary(call, handler, metadata) {
if (!call.metadataSent) {
call.metadataSent = true;
var batch = {};
- batch[grpc.opType.SEND_INITIAL_METADATA] = responseMetadata;
+ batch[grpc.opType.SEND_INITIAL_METADATA] =
+ responseMetadata._getCoreRepresentation();
call.startBatch(batch, function() {});
}
};
@@ -478,7 +491,7 @@ function handleUnary(call, handler, metadata) {
* @access private
* @param {grpc.Call} call The call to handle
* @param {Object} handler Request handler object for the method that was called
- * @param {Object} metadata Metadata from the client
+ * @param {Metadata} metadata Metadata from the client
*/
function handleServerStreaming(call, handler, metadata) {
var stream = new ServerWritableStream(call, handler.serialize);
@@ -507,7 +520,7 @@ function handleServerStreaming(call, handler, metadata) {
* @access private
* @param {grpc.Call} call The call to handle
* @param {Object} handler Request handler object for the method that was called
- * @param {Object} metadata Metadata from the client
+ * @param {Metadata} metadata Metadata from the client
*/
function handleClientStreaming(call, handler, metadata) {
var stream = new ServerReadableStream(call, handler.deserialize);
@@ -515,7 +528,8 @@ function handleClientStreaming(call, handler, metadata) {
if (!call.metadataSent) {
call.metadataSent = true;
var batch = {};
- batch[grpc.opType.SEND_INITIAL_METADATA] = responseMetadata;
+ batch[grpc.opType.SEND_INITIAL_METADATA] =
+ responseMetadata._getCoreRepresentation();
call.startBatch(batch, function() {});
}
};
@@ -542,7 +556,7 @@ function handleClientStreaming(call, handler, metadata) {
* @access private
* @param {grpc.Call} call The call to handle
* @param {Object} handler Request handler object for the method that was called
- * @param {Object} metadata Metadata from the client
+ * @param {Metadata} metadata Metadata from the client
*/
function handleBidiStreaming(call, handler, metadata) {
var stream = new ServerDuplexStream(call, handler.serialize,
@@ -599,7 +613,7 @@ function Server(options) {
var details = event.new_call;
var call = details.call;
var method = details.method;
- var metadata = details.metadata;
+ var metadata = Metadata._fromCoreRepresentation(details.metadata);
if (method === null) {
return;
}
@@ -609,7 +623,8 @@ function Server(options) {
handler = handlers[method];
} else {
var batch = {};
- batch[grpc.opType.SEND_INITIAL_METADATA] = {};
+ batch[grpc.opType.SEND_INITIAL_METADATA] =
+ (new Metadata())._getCoreRepresentation();
batch[grpc.opType.SEND_STATUS_FROM_SERVER] = {
code: grpc.status.UNIMPLEMENTED,
details: 'This method is not available on this server.',
@@ -623,11 +638,26 @@ function Server(options) {
}
server.requestCall(handleNewCall);
};
+
+ /**
+ * Gracefully shuts down the server. The server will stop receiving new calls,
+ * and any pending calls will complete. The callback will be called when all
+ * pending calls have completed and the server is fully shut down. This method
+ * is idempotent with itself and forceShutdown.
+ * @param {function()} callback The shutdown complete callback
+ */
+ this.tryShutdown = function(callback) {
+ server.tryShutdown(callback);
+ };
+
/**
- * Shuts down the server.
+ * Forcibly shuts down the server. The server will stop receiving new calls
+ * and cancel all pending calls. When it returns, the server has shut down.
+ * This method is idempotent with itself and tryShutdown, and it will trigger
+ * any outstanding tryShutdown callbacks.
*/
- this.shutdown = function() {
- server.shutdown();
+ this.forceShutdown = function() {
+ server.forceShutdown();
};
}
diff --git a/src/node/test/call_test.js b/src/node/test/call_test.js
index 8d0f20b074..e7f071bcd5 100644
--- a/src/node/test/call_test.js
+++ b/src/node/test/call_test.js
@@ -61,7 +61,7 @@ describe('call', function() {
channel = new grpc.Channel('localhost:' + port, insecureCreds);
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
describe('constructor', function() {
it('should reject anything less than 3 arguments', function() {
diff --git a/src/node/test/end_to_end_test.js b/src/node/test/end_to_end_test.js
index 7574d98b8a..4b8da3bfb1 100644
--- a/src/node/test/end_to_end_test.js
+++ b/src/node/test/end_to_end_test.js
@@ -70,7 +70,7 @@ describe('end-to-end', function() {
channel = new grpc.Channel('localhost:' + port_num, insecureCreds);
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('should start and end a request without error', function(complete) {
var done = multiDone(complete, 2);
diff --git a/src/node/test/health_test.js b/src/node/test/health_test.js
index 04959f5f55..9267bff7eb 100644
--- a/src/node/test/health_test.js
+++ b/src/node/test/health_test.js
@@ -57,7 +57,7 @@ describe('Health Checking', function() {
grpc.Credentials.createInsecure());
});
after(function() {
- healthServer.shutdown();
+ healthServer.forceShutdown();
});
it('should say an enabled service is SERVING', function(done) {
healthClient.check({service: ''}, function(err, response) {
diff --git a/src/node/test/interop_sanity_test.js b/src/node/test/interop_sanity_test.js
index 0a5eb29c0c..2ca07c1d50 100644
--- a/src/node/test/interop_sanity_test.js
+++ b/src/node/test/interop_sanity_test.js
@@ -51,7 +51,7 @@ describe('Interop tests', function() {
done();
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
// This depends on not using a binary stream
it('should pass empty_unary', function(done) {
diff --git a/src/node/test/math_client_test.js b/src/node/test/math_client_test.js
index ef01870a4c..80b0c5ff2a 100644
--- a/src/node/test/math_client_test.js
+++ b/src/node/test/math_client_test.js
@@ -59,7 +59,7 @@ describe('Math client', function() {
done();
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('should handle a single request', function(done) {
var arg = {dividend: 7, divisor: 4};
diff --git a/src/node/test/metadata_test.js b/src/node/test/metadata_test.js
new file mode 100644
index 0000000000..86383f1bad
--- /dev/null
+++ b/src/node/test/metadata_test.js
@@ -0,0 +1,193 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+'use strict';
+
+var Metadata = require('../src/metadata.js');
+
+var assert = require('assert');
+
+describe('Metadata', function() {
+ var metadata;
+ beforeEach(function() {
+ metadata = new Metadata();
+ });
+ describe('#set', function() {
+ it('Only accepts string values for non "-bin" keys', function() {
+ assert.throws(function() {
+ metadata.set('key', new Buffer('value'));
+ });
+ assert.doesNotThrow(function() {
+ metadata.set('key', 'value');
+ });
+ });
+ it('Only accepts Buffer values for "-bin" keys', function() {
+ assert.throws(function() {
+ metadata.set('key-bin', 'value');
+ });
+ assert.doesNotThrow(function() {
+ metadata.set('key-bin', new Buffer('value'));
+ });
+ });
+ it('Rejects invalid keys', function() {
+ assert.throws(function() {
+ metadata.set('key$', 'value');
+ });
+ assert.throws(function() {
+ metadata.set('', 'value');
+ });
+ });
+ it('Rejects values with non-ASCII characters', function() {
+ assert.throws(function() {
+ metadata.set('key', 'résumé');
+ });
+ });
+ it('Saves values that can be retrieved', function() {
+ metadata.set('key', 'value');
+ assert.deepEqual(metadata.get('key'), ['value']);
+ });
+ it('Overwrites previous values', function() {
+ metadata.set('key', 'value1');
+ metadata.set('key', 'value2');
+ assert.deepEqual(metadata.get('key'), ['value2']);
+ });
+ it('Normalizes keys', function() {
+ metadata.set('Key', 'value1');
+ assert.deepEqual(metadata.get('key'), ['value1']);
+ metadata.set('KEY', 'value2');
+ assert.deepEqual(metadata.get('key'), ['value2']);
+ });
+ });
+ describe('#add', function() {
+ it('Only accepts string values for non "-bin" keys', function() {
+ assert.throws(function() {
+ metadata.add('key', new Buffer('value'));
+ });
+ assert.doesNotThrow(function() {
+ metadata.add('key', 'value');
+ });
+ });
+ it('Only accepts Buffer values for "-bin" keys', function() {
+ assert.throws(function() {
+ metadata.add('key-bin', 'value');
+ });
+ assert.doesNotThrow(function() {
+ metadata.add('key-bin', new Buffer('value'));
+ });
+ });
+ it('Rejects invalid keys', function() {
+ assert.throws(function() {
+ metadata.add('key$', 'value');
+ });
+ assert.throws(function() {
+ metadata.add('', 'value');
+ });
+ });
+ it('Saves values that can be retrieved', function() {
+ metadata.add('key', 'value');
+ assert.deepEqual(metadata.get('key'), ['value']);
+ });
+ it('Combines with previous values', function() {
+ metadata.add('key', 'value1');
+ metadata.add('key', 'value2');
+ assert.deepEqual(metadata.get('key'), ['value1', 'value2']);
+ });
+ it('Normalizes keys', function() {
+ metadata.add('Key', 'value1');
+ assert.deepEqual(metadata.get('key'), ['value1']);
+ metadata.add('KEY', 'value2');
+ assert.deepEqual(metadata.get('key'), ['value1', 'value2']);
+ });
+ });
+ describe('#remove', function() {
+ it('clears values from a key', function() {
+ metadata.add('key', 'value');
+ metadata.remove('key');
+ assert.deepEqual(metadata.get('key'), []);
+ });
+ it('Normalizes keys', function() {
+ metadata.add('key', 'value');
+ metadata.remove('KEY');
+ assert.deepEqual(metadata.get('key'), []);
+ });
+ });
+ describe('#get', function() {
+ beforeEach(function() {
+ metadata.add('key', 'value1');
+ metadata.add('key', 'value2');
+ metadata.add('key-bin', new Buffer('value'));
+ });
+ it('gets all values associated with a key', function() {
+ assert.deepEqual(metadata.get('key'), ['value1', 'value2']);
+ });
+ it('Normalizes keys', function() {
+ assert.deepEqual(metadata.get('KEY'), ['value1', 'value2']);
+ });
+ it('returns an empty list for non-existent keys', function() {
+ assert.deepEqual(metadata.get('non-existent-key'), []);
+ });
+ it('returns Buffers for "-bin" keys', function() {
+ assert(metadata.get('key-bin')[0] instanceof Buffer);
+ });
+ });
+ describe('#getMap', function() {
+ it('gets a map of keys to values', function() {
+ metadata.add('key1', 'value1');
+ metadata.add('Key2', 'value2');
+ metadata.add('KEY3', 'value3');
+ assert.deepEqual(metadata.getMap(),
+ {key1: 'value1',
+ key2: 'value2',
+ key3: 'value3'});
+ });
+ });
+ describe('#clone', function() {
+ it('retains values from the original', function() {
+ metadata.add('key', 'value');
+ var copy = metadata.clone();
+ assert.deepEqual(copy.get('key'), ['value']);
+ });
+ it('Does not see newly added values', function() {
+ metadata.add('key', 'value1');
+ var copy = metadata.clone();
+ metadata.add('key', 'value2');
+ assert.deepEqual(copy.get('key'), ['value1']);
+ });
+ it('Does not add new values to the original', function() {
+ metadata.add('key', 'value1');
+ var copy = metadata.clone();
+ copy.add('key', 'value2');
+ assert.deepEqual(metadata.get('key'), ['value1']);
+ });
+ });
+});
diff --git a/src/node/test/server_test.js b/src/node/test/server_test.js
index 78bac8da29..1e69d52e58 100644
--- a/src/node/test/server_test.js
+++ b/src/node/test/server_test.js
@@ -92,7 +92,7 @@ describe('server', function() {
server.addHttp2Port('0.0.0.0:0', grpc.ServerCredentials.createInsecure());
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('should start without error', function() {
assert.doesNotThrow(function() {
@@ -100,4 +100,33 @@ describe('server', function() {
});
});
});
+ describe('shutdown', function() {
+ var server;
+ beforeEach(function() {
+ server = new grpc.Server();
+ server.addHttp2Port('0.0.0.0:0', grpc.ServerCredentials.createInsecure());
+ server.start();
+ });
+ afterEach(function() {
+ server.forceShutdown();
+ });
+ it('tryShutdown should shutdown successfully', function(done) {
+ server.tryShutdown(done);
+ });
+ it('forceShutdown should shutdown successfully', function() {
+ server.forceShutdown();
+ });
+ it('tryShutdown should be idempotent', function(done) {
+ server.tryShutdown(done);
+ server.tryShutdown(function() {});
+ });
+ it('forceShutdown should be idempotent', function() {
+ server.forceShutdown();
+ server.forceShutdown();
+ });
+ it('forceShutdown should trigger tryShutdown', function(done) {
+ server.tryShutdown(done);
+ server.forceShutdown();
+ });
+ });
});
diff --git a/src/node/test/surface_test.js b/src/node/test/surface_test.js
index ec7ed87728..7c2a8d7258 100644
--- a/src/node/test/surface_test.js
+++ b/src/node/test/surface_test.js
@@ -104,7 +104,7 @@ describe('Server.prototype.addProtoService', function() {
server = new grpc.Server();
});
afterEach(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('Should succeed with a single service', function() {
assert.doesNotThrow(function() {
@@ -148,7 +148,7 @@ describe('Client#$waitForReady', function() {
client = new Client('localhost:' + port, grpc.Credentials.createInsecure());
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('should complete when called alone', function(done) {
client.$waitForReady(Infinity, function(error) {
@@ -203,7 +203,7 @@ describe('Echo service', function() {
server.start();
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('should echo the recieved message directly', function(done) {
client.echo({value: 'test value', value2: 3}, function(error, response) {
@@ -248,7 +248,7 @@ describe('Generic client and server', function() {
grpc.Credentials.createInsecure());
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('Should respond with a capitalized string', function(done) {
client.capitalize('abc', function(err, response) {
@@ -262,6 +262,7 @@ describe('Generic client and server', function() {
describe('Echo metadata', function() {
var client;
var server;
+ var metadata;
before(function() {
var test_proto = ProtoBuf.loadProtoFile(__dirname + '/test_service.proto');
var test_service = test_proto.lookup('TestService');
@@ -294,42 +295,44 @@ describe('Echo metadata', function() {
var Client = surface_client.makeProtobufClientConstructor(test_service);
client = new Client('localhost:' + port, grpc.Credentials.createInsecure());
server.start();
+ metadata = new grpc.Metadata();
+ metadata.set('key', 'value');
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('with unary call', function(done) {
var call = client.unary({}, function(err, data) {
assert.ifError(err);
- }, {key: ['value']});
+ }, metadata);
call.on('metadata', function(metadata) {
- assert.deepEqual(metadata.key, ['value']);
+ assert.deepEqual(metadata.get('key'), ['value']);
done();
});
});
it('with client stream call', function(done) {
var call = client.clientStream(function(err, data) {
assert.ifError(err);
- }, {key: ['value']});
+ }, metadata);
call.on('metadata', function(metadata) {
- assert.deepEqual(metadata.key, ['value']);
+ assert.deepEqual(metadata.get('key'), ['value']);
done();
});
call.end();
});
it('with server stream call', function(done) {
- var call = client.serverStream({}, {key: ['value']});
+ var call = client.serverStream({}, metadata);
call.on('data', function() {});
call.on('metadata', function(metadata) {
- assert.deepEqual(metadata.key, ['value']);
+ assert.deepEqual(metadata.get('key'), ['value']);
done();
});
});
it('with bidi stream call', function(done) {
- var call = client.bidiStream({key: ['value']});
+ var call = client.bidiStream(metadata);
call.on('data', function() {});
call.on('metadata', function(metadata) {
- assert.deepEqual(metadata.key, ['value']);
+ assert.deepEqual(metadata.get('key'), ['value']);
done();
});
call.end();
@@ -337,9 +340,10 @@ describe('Echo metadata', function() {
it('shows the correct user-agent string', function(done) {
var version = require('../package.json').version;
var call = client.unary({}, function(err, data) { assert.ifError(err); },
- {key: ['value']});
+ metadata);
call.on('metadata', function(metadata) {
- assert(_.startsWith(metadata['user-agent'], 'grpc-node/' + version));
+ assert(_.startsWith(metadata.get('user-agent')[0],
+ 'grpc-node/' + version));
done();
});
});
@@ -354,13 +358,15 @@ describe('Other conditions', function() {
var test_proto = ProtoBuf.loadProtoFile(__dirname + '/test_service.proto');
test_service = test_proto.lookup('TestService');
server = new grpc.Server();
+ var trailer_metadata = new grpc.Metadata();
+ trailer_metadata.add('trailer-present', 'yes');
server.addProtoService(test_service, {
unary: function(call, cb) {
var req = call.request;
if (req.error) {
- cb(new Error('Requested error'), null, {trailer_present: ['yes']});
+ cb(new Error('Requested error'), null, trailer_metadata);
} else {
- cb(null, {count: 1}, {trailer_present: ['yes']});
+ cb(null, {count: 1}, trailer_metadata);
}
},
clientStream: function(stream, cb){
@@ -369,14 +375,14 @@ describe('Other conditions', function() {
stream.on('data', function(data) {
if (data.error) {
errored = true;
- cb(new Error('Requested error'), null, {trailer_present: ['yes']});
+ cb(new Error('Requested error'), null, trailer_metadata);
} else {
count += 1;
}
});
stream.on('end', function() {
if (!errored) {
- cb(null, {count: count}, {trailer_present: ['yes']});
+ cb(null, {count: count}, trailer_metadata);
}
});
},
@@ -384,13 +390,13 @@ describe('Other conditions', function() {
var req = stream.request;
if (req.error) {
var err = new Error('Requested error');
- err.metadata = {trailer_present: ['yes']};
+ err.metadata = trailer_metadata;
stream.emit('error', err);
} else {
for (var i = 0; i < 5; i++) {
stream.write({count: i});
}
- stream.end({trailer_present: ['yes']});
+ stream.end(trailer_metadata);
}
},
bidiStream: function(stream) {
@@ -398,10 +404,8 @@ describe('Other conditions', function() {
stream.on('data', function(data) {
if (data.error) {
var err = new Error('Requested error');
- err.metadata = {
- trailer_present: ['yes'],
- count: ['' + count]
- };
+ err.metadata = trailer_metadata.clone();
+ err.metadata.add('count', '' + count);
stream.emit('error', err);
} else {
stream.write({count: count});
@@ -409,7 +413,7 @@ describe('Other conditions', function() {
}
});
stream.on('end', function() {
- stream.end({trailer_present: ['yes']});
+ stream.end(trailer_metadata);
});
}
});
@@ -419,7 +423,7 @@ describe('Other conditions', function() {
server.start();
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('channel.getTarget should be available', function() {
assert.strictEqual(typeof client.channel.getTarget(), 'string');
@@ -510,7 +514,7 @@ describe('Other conditions', function() {
assert.ifError(err);
});
call.on('status', function(status) {
- assert.deepEqual(status.metadata.trailer_present, ['yes']);
+ assert.deepEqual(status.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -519,7 +523,7 @@ describe('Other conditions', function() {
assert(err);
});
call.on('status', function(status) {
- assert.deepEqual(status.metadata.trailer_present, ['yes']);
+ assert.deepEqual(status.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -531,7 +535,7 @@ describe('Other conditions', function() {
call.write({error: false});
call.end();
call.on('status', function(status) {
- assert.deepEqual(status.metadata.trailer_present, ['yes']);
+ assert.deepEqual(status.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -543,7 +547,7 @@ describe('Other conditions', function() {
call.write({error: true});
call.end();
call.on('status', function(status) {
- assert.deepEqual(status.metadata.trailer_present, ['yes']);
+ assert.deepEqual(status.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -552,7 +556,7 @@ describe('Other conditions', function() {
call.on('data', function(){});
call.on('status', function(status) {
assert.strictEqual(status.code, grpc.status.OK);
- assert.deepEqual(status.metadata.trailer_present, ['yes']);
+ assert.deepEqual(status.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -560,7 +564,7 @@ describe('Other conditions', function() {
var call = client.serverStream({error: true});
call.on('data', function(){});
call.on('error', function(error) {
- assert.deepEqual(error.metadata.trailer_present, ['yes']);
+ assert.deepEqual(error.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -572,7 +576,7 @@ describe('Other conditions', function() {
call.on('data', function(){});
call.on('status', function(status) {
assert.strictEqual(status.code, grpc.status.OK);
- assert.deepEqual(status.metadata.trailer_present, ['yes']);
+ assert.deepEqual(status.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -583,7 +587,7 @@ describe('Other conditions', function() {
call.end();
call.on('data', function(){});
call.on('error', function(error) {
- assert.deepEqual(error.metadata.trailer_present, ['yes']);
+ assert.deepEqual(error.metadata.get('trailer-present'), ['yes']);
done();
});
});
@@ -681,7 +685,7 @@ describe('Other conditions', function() {
});
afterEach(function() {
console.log('Shutting down server');
- proxy.shutdown();
+ proxy.forceShutdown();
});
describe('Cancellation', function() {
it('With a unary call', function(done) {
@@ -847,7 +851,7 @@ describe('Cancelling surface client', function() {
server.start();
});
after(function() {
- server.shutdown();
+ server.forceShutdown();
});
it('Should correctly cancel a unary call', function(done) {
var call = client.div({'divisor': 0, 'dividend': 0}, function(err, resp) {
diff --git a/src/objective-c/GRPCClient/private/GRPCSecureChannel.m b/src/objective-c/GRPCClient/private/GRPCSecureChannel.m
index 0a54804bb2..ce16655330 100644
--- a/src/objective-c/GRPCClient/private/GRPCSecureChannel.m
+++ b/src/objective-c/GRPCClient/private/GRPCSecureChannel.m
@@ -49,7 +49,7 @@ static grpc_credentials *CertificatesAtPath(NSString *path, NSError **errorPtr)
// Passing NULL to grpc_ssl_credentials_create produces behavior we don't want, so return.
return NULL;
}
- return grpc_ssl_credentials_create(contentInASCII.bytes, NULL);
+ return grpc_ssl_credentials_create(contentInASCII.bytes, NULL, NULL);
}
@implementation GRPCSecureChannel
@@ -101,8 +101,9 @@ static grpc_credentials *CertificatesAtPath(NSString *path, NSError **errorPtr)
- (instancetype)initWithHost:(NSString *)host
credentials:(grpc_credentials *)credentials
args:(grpc_channel_args *)args {
- return (self =
- [super initWithChannel:grpc_secure_channel_create(credentials, host.UTF8String, args)]);
+ return (self = [super
+ initWithChannel:grpc_secure_channel_create(
+ credentials, host.UTF8String, args, NULL)]);
}
// TODO(jcanizales): GRPCSecureChannel and GRPCUnsecuredChannel are just convenience initializers
diff --git a/src/objective-c/README.md b/src/objective-c/README.md
index e997b76d14..6c27657def 100644
--- a/src/objective-c/README.md
+++ b/src/objective-c/README.md
@@ -30,7 +30,7 @@ proceed.
## Write your API declaration in proto format
For this you can consult the [Protocol Buffers][]' official documentation, or learn from a quick
-example [here](https://github.com/grpc/grpc-common#defining-a-service).
+example [here](https://github.com/grpc/grpc/tree/master/examples#defining-a-service).
<a name="cocoapods"></a>
## Integrate a proto library in your project
diff --git a/src/objective-c/tests/LocalClearTextTests.m b/src/objective-c/tests/LocalClearTextTests.m
index 4317614dd9..d01fe91afa 100644
--- a/src/objective-c/tests/LocalClearTextTests.m
+++ b/src/objective-c/tests/LocalClearTextTests.m
@@ -42,7 +42,7 @@
#import <RxLibrary/GRXWriter+Immediate.h>
// These tests require a gRPC "RouteGuide" sample server to be running locally. You can compile and
-// run one by following the instructions here: https://github.com/grpc/grpc-common/blob/master/cpp/cpptutorial.md#try-it-out
+// run one by following the instructions here: https://github.com/grpc/grpc/blob/master/examples/cpp/cpptutorial.md#try-it-out
// Be sure to have the C gRPC library installed in your system (for example, by having followed the
// instructions at https://github.com/grpc/homebrew-grpc
diff --git a/src/php/ext/grpc/channel.c b/src/php/ext/grpc/channel.c
index 7a981675de..a4313b6bd4 100644
--- a/src/php/ext/grpc/channel.c
+++ b/src/php/ext/grpc/channel.c
@@ -169,7 +169,7 @@ PHP_METHOD(Channel, __construct) {
} else {
gpr_log(GPR_DEBUG, "Initialized secure channel");
channel->wrapped =
- grpc_secure_channel_create(creds->wrapped, target, &args);
+ grpc_secure_channel_create(creds->wrapped, target, &args, NULL);
}
efree(args.args);
}
diff --git a/src/php/ext/grpc/credentials.c b/src/php/ext/grpc/credentials.c
index 01cb94e3aa..0eba6608bb 100644
--- a/src/php/ext/grpc/credentials.c
+++ b/src/php/ext/grpc/credentials.c
@@ -130,7 +130,7 @@ PHP_METHOD(Credentials, createSsl) {
}
grpc_credentials *creds = grpc_ssl_credentials_create(
pem_root_certs,
- pem_key_cert_pair.private_key == NULL ? NULL : &pem_key_cert_pair);
+ pem_key_cert_pair.private_key == NULL ? NULL : &pem_key_cert_pair, NULL);
zval *creds_object = grpc_php_wrap_credentials(creds);
RETURN_DESTROY_ZVAL(creds_object);
}
@@ -160,7 +160,7 @@ PHP_METHOD(Credentials, createComposite) {
(wrapped_grpc_credentials *)zend_object_store_get_object(
cred2_obj TSRMLS_CC);
grpc_credentials *creds =
- grpc_composite_credentials_create(cred1->wrapped, cred2->wrapped);
+ grpc_composite_credentials_create(cred1->wrapped, cred2->wrapped, NULL);
zval *creds_object = grpc_php_wrap_credentials(creds);
RETURN_DESTROY_ZVAL(creds_object);
}
@@ -170,7 +170,7 @@ PHP_METHOD(Credentials, createComposite) {
* @return Credentials The new GCE credentials object
*/
PHP_METHOD(Credentials, createGce) {
- grpc_credentials *creds = grpc_compute_engine_credentials_create();
+ grpc_credentials *creds = grpc_compute_engine_credentials_create(NULL);
zval *creds_object = grpc_php_wrap_credentials(creds);
RETURN_DESTROY_ZVAL(creds_object);
}
diff --git a/src/php/ext/grpc/server_credentials.c b/src/php/ext/grpc/server_credentials.c
index e9183c4598..79188246bc 100644
--- a/src/php/ext/grpc/server_credentials.c
+++ b/src/php/ext/grpc/server_credentials.c
@@ -118,7 +118,7 @@ PHP_METHOD(ServerCredentials, createSsl) {
/* TODO: add a force_client_auth field in ServerCredentials and pass it as
* the last parameter. */
grpc_server_credentials *creds = grpc_ssl_server_credentials_create(
- pem_root_certs, &pem_key_cert_pair, 1, 0);
+ pem_root_certs, &pem_key_cert_pair, 1, 0, NULL);
zval *creds_object = grpc_php_wrap_server_credentials(creds);
RETURN_DESTROY_ZVAL(creds_object);
}
diff --git a/src/php/tests/generated_code/AbstractGeneratedCodeTest.php b/src/php/tests/generated_code/AbstractGeneratedCodeTest.php
index 287621d930..a368dd4ee0 100644
--- a/src/php/tests/generated_code/AbstractGeneratedCodeTest.php
+++ b/src/php/tests/generated_code/AbstractGeneratedCodeTest.php
@@ -47,6 +47,10 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
$this->assertTrue(self::$client->waitForReady(250000));
}
+ public function testGetTarget() {
+ $this->assertTrue(is_string(self::$client->getTarget()));
+ }
+
public function testSimpleRequest() {
$div_arg = new math\DivArgs();
$div_arg->setDividend(7);
diff --git a/src/php/tests/interop/interop_client.php b/src/php/tests/interop/interop_client.php
index 376d306da0..bd15ee4303 100755
--- a/src/php/tests/interop/interop_client.php
+++ b/src/php/tests/interop/interop_client.php
@@ -332,11 +332,7 @@ if (in_array($args['test_case'], array(
$opts['update_metadata'] = $auth->getUpdateMetadataFunc();
}
-$internal_stub = new Grpc\BaseStub($server_address, $opts);
-hardAssert(is_string($internal_stub->getTarget()),
- 'Unexpected target URI value');
-
-$stub = new grpc\testing\TestServiceClient($internal_stub);
+$stub = new grpc\testing\TestServiceClient($server_address, $opts);
echo "Connecting to $server_address\n";
echo "Running test case $args[test_case]\n";
@@ -372,6 +368,11 @@ switch ($args['test_case']) {
case 'jwt_token_creds':
jwtTokenCreds($stub, $args);
break;
+ case 'cancel_after_begin':
+ // Currently unimplementable with the current API design
+ // Specifically, in the ClientStreamingCall->start() method, the
+ // messages are sent immediately after metadata is sent. There is
+ // currently no way to cancel before messages are sent.
default:
exit(1);
}
diff --git a/src/python/README.md b/src/python/README.md
index de0142db05..affce64884 100644
--- a/src/python/README.md
+++ b/src/python/README.md
@@ -52,9 +52,19 @@ BUILDING FROM SOURCE
---------------------
- Clone this repository
+- Initialize the git submodules
+```
+$ git submodule update --init
+```
+
+- Make the libraries
+```
+$ make
+```
+
- Use build_python.sh to build the Python code and install it into a virtual environment
```
-$ tools/run_tests/build_python.sh
+$ CONFIG=opt tools/run_tests/build_python.sh 2.7
```
TESTING
@@ -62,7 +72,7 @@ TESTING
- Use run_python.sh to run gRPC as it was installed into the virtual environment
```
-$ tools/run_tests/run_python.sh
+$ CONFIG=opt PYVER=2.7 tools/run_tests/run_python.sh
```
PACKAGING
diff --git a/src/python/grpcio/grpc/_adapter/_c/types/channel.c b/src/python/grpcio/grpc/_adapter/_c/types/channel.c
index c577ac05eb..79d39c4391 100644
--- a/src/python/grpcio/grpc/_adapter/_c/types/channel.c
+++ b/src/python/grpcio/grpc/_adapter/_c/types/channel.c
@@ -106,7 +106,8 @@ Channel *pygrpc_Channel_new(
}
self = (Channel *)type->tp_alloc(type, 0);
if (creds) {
- self->c_chan = grpc_secure_channel_create(creds->c_creds, target, &c_args);
+ self->c_chan =
+ grpc_secure_channel_create(creds->c_creds, target, &c_args, NULL);
} else {
self->c_chan = grpc_insecure_channel_create(target, &c_args, NULL);
}
@@ -164,7 +165,7 @@ PyObject *pygrpc_Channel_watch_connectivity_state(
int last_observed_state;
CompletionQueue *completion_queue;
char *keywords[] = {"last_observed_state", "deadline",
- "completion_queue", "tag"};
+ "completion_queue", "tag", NULL};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "idO!O:watch_connectivity_state", keywords,
&last_observed_state, &deadline, &pygrpc_CompletionQueue_type,
diff --git a/src/python/grpcio/grpc/_adapter/_c/types/client_credentials.c b/src/python/grpcio/grpc/_adapter/_c/types/client_credentials.c
index e314c15324..36fd207464 100644
--- a/src/python/grpcio/grpc/_adapter/_c/types/client_credentials.c
+++ b/src/python/grpcio/grpc/_adapter/_c/types/client_credentials.c
@@ -135,9 +135,10 @@ ClientCredentials *pygrpc_ClientCredentials_ssl(
if (private_key && cert_chain) {
key_cert_pair.private_key = private_key;
key_cert_pair.cert_chain = cert_chain;
- self->c_creds = grpc_ssl_credentials_create(root_certs, &key_cert_pair);
+ self->c_creds =
+ grpc_ssl_credentials_create(root_certs, &key_cert_pair, NULL);
} else {
- self->c_creds = grpc_ssl_credentials_create(root_certs, NULL);
+ self->c_creds = grpc_ssl_credentials_create(root_certs, NULL, NULL);
}
if (!self->c_creds) {
Py_DECREF(self);
@@ -159,8 +160,8 @@ ClientCredentials *pygrpc_ClientCredentials_composite(
return NULL;
}
self = (ClientCredentials *)type->tp_alloc(type, 0);
- self->c_creds = grpc_composite_credentials_create(
- creds1->c_creds, creds2->c_creds);
+ self->c_creds =
+ grpc_composite_credentials_create(creds1->c_creds, creds2->c_creds, NULL);
if (!self->c_creds) {
Py_DECREF(self);
PyErr_SetString(PyExc_RuntimeError, "couldn't create composite credentials");
@@ -172,7 +173,7 @@ ClientCredentials *pygrpc_ClientCredentials_composite(
ClientCredentials *pygrpc_ClientCredentials_compute_engine(
PyTypeObject *type, PyObject *ignored) {
ClientCredentials *self = (ClientCredentials *)type->tp_alloc(type, 0);
- self->c_creds = grpc_compute_engine_credentials_create();
+ self->c_creds = grpc_compute_engine_credentials_create(NULL);
if (!self->c_creds) {
Py_DECREF(self);
PyErr_SetString(PyExc_RuntimeError,
@@ -195,7 +196,7 @@ ClientCredentials *pygrpc_ClientCredentials_service_account(
}
self = (ClientCredentials *)type->tp_alloc(type, 0);
self->c_creds = grpc_service_account_credentials_create(
- json_key, scope, pygrpc_cast_double_to_gpr_timespec(lifetime));
+ json_key, scope, pygrpc_cast_double_to_gpr_timespec(lifetime), NULL);
if (!self->c_creds) {
Py_DECREF(self);
PyErr_SetString(PyExc_RuntimeError,
@@ -218,7 +219,7 @@ ClientCredentials *pygrpc_ClientCredentials_jwt(
}
self = (ClientCredentials *)type->tp_alloc(type, 0);
self->c_creds = grpc_service_account_jwt_access_credentials_create(
- json_key, pygrpc_cast_double_to_gpr_timespec(lifetime));
+ json_key, pygrpc_cast_double_to_gpr_timespec(lifetime), NULL);
if (!self->c_creds) {
Py_DECREF(self);
PyErr_SetString(PyExc_RuntimeError, "couldn't create JWT credentials");
@@ -237,7 +238,8 @@ ClientCredentials *pygrpc_ClientCredentials_refresh_token(
return NULL;
}
self = (ClientCredentials *)type->tp_alloc(type, 0);
- self->c_creds = grpc_refresh_token_credentials_create(json_refresh_token);
+ self->c_creds =
+ grpc_refresh_token_credentials_create(json_refresh_token, NULL);
if (!self->c_creds) {
Py_DECREF(self);
PyErr_SetString(PyExc_RuntimeError,
@@ -259,7 +261,7 @@ ClientCredentials *pygrpc_ClientCredentials_iam(
}
self = (ClientCredentials *)type->tp_alloc(type, 0);
self->c_creds = grpc_iam_credentials_create(authorization_token,
- authority_selector);
+ authority_selector, NULL);
if (!self->c_creds) {
Py_DECREF(self);
PyErr_SetString(PyExc_RuntimeError, "couldn't create IAM credentials");
diff --git a/src/python/grpcio/grpc/_adapter/_c/types/server_credentials.c b/src/python/grpcio/grpc/_adapter/_c/types/server_credentials.c
index f6859b79d7..df51a99b6a 100644
--- a/src/python/grpcio/grpc/_adapter/_c/types/server_credentials.c
+++ b/src/python/grpcio/grpc/_adapter/_c/types/server_credentials.c
@@ -99,11 +99,13 @@ ServerCredentials *pygrpc_ServerCredentials_ssl(
const char *root_certs;
PyObject *py_key_cert_pairs;
grpc_ssl_pem_key_cert_pair *key_cert_pairs;
+ int force_client_auth;
size_t num_key_cert_pairs;
size_t i;
- static char *keywords[] = {"root_certs", "key_cert_pairs", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "zO:ssl", keywords,
- &root_certs, &py_key_cert_pairs)) {
+ static char *keywords[] = {
+ "root_certs", "key_cert_pairs", "force_client_auth", NULL};
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "zOi:ssl", keywords,
+ &root_certs, &py_key_cert_pairs, &force_client_auth)) {
return NULL;
}
if (!PyList_Check(py_key_cert_pairs)) {
@@ -128,11 +130,8 @@ ServerCredentials *pygrpc_ServerCredentials_ssl(
}
self = (ServerCredentials *)type->tp_alloc(type, 0);
- /* TODO: Add a force_client_auth parameter in the python object and pass it
- here as the last arg. */
self->c_creds = grpc_ssl_server_credentials_create(
- root_certs, key_cert_pairs, num_key_cert_pairs, 0);
+ root_certs, key_cert_pairs, num_key_cert_pairs, force_client_auth, NULL);
gpr_free(key_cert_pairs);
return self;
}
-
diff --git a/src/python/grpcio/grpc/_adapter/_intermediary_low.py b/src/python/grpcio/grpc/_adapter/_intermediary_low.py
index e7bf9dc462..06358e72bc 100644
--- a/src/python/grpcio/grpc/_adapter/_intermediary_low.py
+++ b/src/python/grpcio/grpc/_adapter/_intermediary_low.py
@@ -255,5 +255,6 @@ class ClientCredentials(object):
class ServerCredentials(object):
"""Adapter from old _low.ServerCredentials interface to new _low.ServerCredentials."""
- def __init__(self, root_credentials, pair_sequence):
- self._internal = _low.ServerCredentials.ssl(root_credentials, list(pair_sequence))
+ def __init__(self, root_credentials, pair_sequence, force_client_auth):
+ self._internal = _low.ServerCredentials.ssl(
+ root_credentials, list(pair_sequence), force_client_auth)
diff --git a/src/python/grpcio/grpc/_adapter/fore.py b/src/python/grpcio/grpc/_adapter/fore.py
index 7d88bda263..daa41e8bde 100644
--- a/src/python/grpcio/grpc/_adapter/fore.py
+++ b/src/python/grpcio/grpc/_adapter/fore.py
@@ -288,7 +288,7 @@ class ForeLink(base_interfaces.ForeLink, activated.Activated):
self._port = self._server.add_http2_addr(address)
else:
server_credentials = _low.ServerCredentials(
- self._root_certificates, self._key_chain_pairs)
+ self._root_certificates, self._key_chain_pairs, False)
self._server = _low.Server(self._completion_queue)
self._port = self._server.add_secure_http2_addr(
address, server_credentials)
diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxd b/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxd
index d065383587..c793774c8d 100644
--- a/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxd
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxd
@@ -332,7 +332,7 @@ cdef extern from "grpc/grpc_security.h":
grpc_server_credentials *grpc_ssl_server_credentials_create(
const char *pem_root_certs,
grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs,
- size_t num_key_cert_pairs);
+ size_t num_key_cert_pairs)
void grpc_server_credentials_release(grpc_server_credentials *creds)
int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr,
diff --git a/src/python/grpcio/grpc/_links/service.py b/src/python/grpcio/grpc/_links/service.py
index 43c4c0e80c..393f80c1cc 100644
--- a/src/python/grpcio/grpc/_links/service.py
+++ b/src/python/grpcio/grpc/_links/service.py
@@ -316,9 +316,8 @@ class _Kernel(object):
call.status(status, call)
self._rpc_states.pop(call, None)
- def add_port(self, port, server_credentials):
+ def add_port(self, address, server_credentials):
with self._lock:
- address = '[::]:%d' % port
if self._server is None:
self._completion_queue = _intermediary_low.CompletionQueue()
self._server = _intermediary_low.Server(self._completion_queue)
@@ -362,17 +361,20 @@ class ServiceLink(links.Link):
"""
@abc.abstractmethod
- def add_port(self, port, server_credentials):
+ def add_port(self, address, server_credentials):
"""Adds a port on which to service RPCs after this link has been started.
Args:
- port: The port on which to service RPCs, or zero to request that a port be
- automatically selected and used.
- server_credentials: A ServerCredentials object, or None for insecure
- service.
+ address: The address on which to service RPCs with a port number of zero
+ requesting that a port number be automatically selected and used.
+ server_credentials: An _intermediary_low.ServerCredentials object, or
+ None for insecure service.
Returns:
- A port on which RPCs will be serviced after this link has been started.
+ A integer port on which RPCs will be serviced after this link has been
+ started. This is typically the same number as the port number contained
+ in the passed address, but will likely be different if the port number
+ contained in the passed address was zero.
"""
raise NotImplementedError()
@@ -417,8 +419,8 @@ class _ServiceLink(ServiceLink):
def join_link(self, link):
self._relay.set_behavior(link.accept_ticket)
- def add_port(self, port, server_credentials):
- return self._kernel.add_port(port, server_credentials)
+ def add_port(self, address, server_credentials):
+ return self._kernel.add_port(address, server_credentials)
def start(self):
self._relay.start()
diff --git a/src/python/grpcio/grpc/beta/__init__.py b/src/python/grpcio/grpc/beta/__init__.py
new file mode 100644
index 0000000000..b89398809f
--- /dev/null
+++ b/src/python/grpcio/grpc/beta/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/src/python/grpcio/grpc/beta/_connectivity_channel.py b/src/python/grpcio/grpc/beta/_connectivity_channel.py
new file mode 100644
index 0000000000..457ede79f2
--- /dev/null
+++ b/src/python/grpcio/grpc/beta/_connectivity_channel.py
@@ -0,0 +1,148 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Affords a connectivity-state-listenable channel."""
+
+import threading
+import time
+
+from grpc._adapter import _low
+from grpc.framework.foundation import callable_util
+
+_CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = (
+ 'Exception calling channel subscription callback!')
+
+
+class ConnectivityChannel(object):
+
+ def __init__(self, low_channel, mapping):
+ self._lock = threading.Lock()
+ self._low_channel = low_channel
+ self._mapping = mapping
+
+ self._polling = False
+ self._connectivity = None
+ self._try_to_connect = False
+ self._callbacks_and_connectivities = []
+ self._delivering = False
+
+ def _deliveries(self, connectivity):
+ callbacks_needing_update = []
+ for callback_and_connectivity in self._callbacks_and_connectivities:
+ callback, callback_connectivity = callback_and_connectivity
+ if callback_connectivity is not connectivity:
+ callbacks_needing_update.append(callback)
+ callback_and_connectivity[1] = connectivity
+ return callbacks_needing_update
+
+ def _deliver(self, initial_connectivity, initial_callbacks):
+ connectivity = initial_connectivity
+ callbacks = initial_callbacks
+ while True:
+ for callback in callbacks:
+ callable_util.call_logging_exceptions(
+ callback, _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE,
+ connectivity)
+ with self._lock:
+ callbacks = self._deliveries(self._connectivity)
+ if callbacks:
+ connectivity = self._connectivity
+ else:
+ self._delivering = False
+ return
+
+ def _spawn_delivery(self, connectivity, callbacks):
+ delivering_thread = threading.Thread(
+ target=self._deliver, args=(connectivity, callbacks,))
+ delivering_thread.start()
+ self._delivering = True
+
+ # TODO(issue 3064): Don't poll.
+ def _poll_connectivity(self, low_channel, initial_try_to_connect):
+ try_to_connect = initial_try_to_connect
+ low_connectivity = low_channel.check_connectivity_state(try_to_connect)
+ with self._lock:
+ self._connectivity = self._mapping[low_connectivity]
+ callbacks = tuple(
+ callback for callback, unused_but_known_to_be_none_connectivity
+ in self._callbacks_and_connectivities)
+ for callback_and_connectivity in self._callbacks_and_connectivities:
+ callback_and_connectivity[1] = self._connectivity
+ if callbacks:
+ self._spawn_delivery(self._connectivity, callbacks)
+ completion_queue = _low.CompletionQueue()
+ while True:
+ low_channel.watch_connectivity_state(
+ low_connectivity, time.time() + 0.2, completion_queue, None)
+ event = completion_queue.next()
+ with self._lock:
+ if not self._callbacks_and_connectivities and not self._try_to_connect:
+ self._polling = False
+ self._connectivity = None
+ completion_queue.shutdown()
+ break
+ try_to_connect = self._try_to_connect
+ self._try_to_connect = False
+ if event.success or try_to_connect:
+ low_connectivity = low_channel.check_connectivity_state(try_to_connect)
+ with self._lock:
+ self._connectivity = self._mapping[low_connectivity]
+ if not self._delivering:
+ callbacks = self._deliveries(self._connectivity)
+ if callbacks:
+ self._spawn_delivery(self._connectivity, callbacks)
+
+ def subscribe(self, callback, try_to_connect):
+ with self._lock:
+ if not self._callbacks_and_connectivities and not self._polling:
+ polling_thread = threading.Thread(
+ target=self._poll_connectivity,
+ args=(self._low_channel, bool(try_to_connect)))
+ polling_thread.start()
+ self._polling = True
+ self._callbacks_and_connectivities.append([callback, None])
+ elif not self._delivering and self._connectivity is not None:
+ self._spawn_delivery(self._connectivity, (callback,))
+ self._try_to_connect |= bool(try_to_connect)
+ self._callbacks_and_connectivities.append(
+ [callback, self._connectivity])
+ else:
+ self._try_to_connect |= bool(try_to_connect)
+ self._callbacks_and_connectivities.append([callback, None])
+
+ def unsubscribe(self, callback):
+ with self._lock:
+ for index, (subscribed_callback, unused_connectivity) in enumerate(
+ self._callbacks_and_connectivities):
+ if callback == subscribed_callback:
+ self._callbacks_and_connectivities.pop(index)
+ break
+
+ def low_channel(self):
+ return self._low_channel
diff --git a/src/python/grpcio/grpc/beta/beta.py b/src/python/grpcio/grpc/beta/beta.py
new file mode 100644
index 0000000000..40cad5e486
--- /dev/null
+++ b/src/python/grpcio/grpc/beta/beta.py
@@ -0,0 +1,114 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Entry points into gRPC Python Beta."""
+
+import enum
+
+from grpc._adapter import _low
+from grpc._adapter import _types
+from grpc.beta import _connectivity_channel
+
+_CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = (
+ 'Exception calling channel subscription callback!')
+
+
+@enum.unique
+class ChannelConnectivity(enum.Enum):
+ """Mirrors grpc_connectivity_state in the gRPC Core.
+
+ Attributes:
+ IDLE: The channel is idle.
+ CONNECTING: The channel is connecting.
+ READY: The channel is ready to conduct RPCs.
+ TRANSIENT_FAILURE: The channel has seen a failure from which it expects to
+ recover.
+ FATAL_FAILURE: The channel has seen a failure from which it cannot recover.
+ """
+
+ IDLE = (_types.ConnectivityState.IDLE, 'idle',)
+ CONNECTING = (_types.ConnectivityState.CONNECTING, 'connecting',)
+ READY = (_types.ConnectivityState.READY, 'ready',)
+ TRANSIENT_FAILURE = (
+ _types.ConnectivityState.TRANSIENT_FAILURE, 'transient failure',)
+ FATAL_FAILURE = (_types.ConnectivityState.FATAL_FAILURE, 'fatal failure',)
+
+_LOW_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY = {
+ state: connectivity for state, connectivity in zip(
+ _types.ConnectivityState, ChannelConnectivity)
+}
+
+
+class Channel(object):
+ """A channel to a remote host through which RPCs may be conducted.
+
+ Only the "subscribe" and "unsubscribe" methods are supported for application
+ use. This class' instance constructor and all other attributes are
+ unsupported.
+ """
+
+ def __init__(self, low_channel):
+ self._connectivity_channel = _connectivity_channel.ConnectivityChannel(
+ low_channel, _LOW_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY)
+
+ def subscribe(self, callback, try_to_connect=None):
+ """Subscribes to this Channel's connectivity.
+
+ Args:
+ callback: A callable to be invoked and passed this Channel's connectivity.
+ The callable will be invoked immediately upon subscription and again for
+ every change to this Channel's connectivity thereafter until it is
+ unsubscribed.
+ try_to_connect: A boolean indicating whether or not this Channel should
+ attempt to connect if it is not already connected and ready to conduct
+ RPCs.
+ """
+ self._connectivity_channel.subscribe(callback, try_to_connect)
+
+ def unsubscribe(self, callback):
+ """Unsubscribes a callback from this Channel's connectivity.
+
+ Args:
+ callback: A callable previously registered with this Channel from having
+ been passed to its "subscribe" method.
+ """
+ self._connectivity_channel.unsubscribe(callback)
+
+
+def create_insecure_channel(host, port):
+ """Creates an insecure Channel to a remote host.
+
+ Args:
+ host: The name of the remote host to which to connect.
+ port: The port of the remote host to which to connect.
+
+ Returns:
+ A Channel to the remote host through which RPCs may be conducted.
+ """
+ return Channel(_low.Channel('%s:%d' % (host, port), ()))
diff --git a/src/python/grpcio/grpc/beta/utilities.py b/src/python/grpcio/grpc/beta/utilities.py
new file mode 100644
index 0000000000..1b5356e3ad
--- /dev/null
+++ b/src/python/grpcio/grpc/beta/utilities.py
@@ -0,0 +1,161 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Utilities for the gRPC Python Beta API."""
+
+import threading
+import time
+
+from grpc.beta import beta
+from grpc.framework.foundation import callable_util
+from grpc.framework.foundation import future
+
+_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE = (
+ 'Exception calling connectivity future "done" callback!')
+
+
+class _ChannelReadyFuture(future.Future):
+
+ def __init__(self, channel):
+ self._condition = threading.Condition()
+ self._channel = channel
+
+ self._matured = False
+ self._cancelled = False
+ self._done_callbacks = []
+
+ def _block(self, timeout):
+ until = None if timeout is None else time.time() + timeout
+ with self._condition:
+ while True:
+ if self._cancelled:
+ raise future.CancelledError()
+ elif self._matured:
+ return
+ else:
+ if until is None:
+ self._condition.wait()
+ else:
+ remaining = until - time.time()
+ if remaining < 0:
+ raise future.TimeoutError()
+ else:
+ self._condition.wait(timeout=remaining)
+
+ def _update(self, connectivity):
+ with self._condition:
+ if not self._cancelled and connectivity is beta.ChannelConnectivity.READY:
+ self._matured = True
+ self._channel.unsubscribe(self._update)
+ self._condition.notify_all()
+ done_callbacks = tuple(self._done_callbacks)
+ self._done_callbacks = None
+ else:
+ return
+
+ for done_callback in done_callbacks:
+ callable_util.call_logging_exceptions(
+ done_callback, _DONE_CALLBACK_EXCEPTION_LOG_MESSAGE, self)
+
+ def cancel(self):
+ with self._condition:
+ if not self._matured:
+ self._cancelled = True
+ self._channel.unsubscribe(self._update)
+ self._condition.notify_all()
+ done_callbacks = tuple(self._done_callbacks)
+ self._done_callbacks = None
+ else:
+ return False
+
+ for done_callback in done_callbacks:
+ callable_util.call_logging_exceptions(
+ done_callback, _DONE_CALLBACK_EXCEPTION_LOG_MESSAGE, self)
+
+ def cancelled(self):
+ with self._condition:
+ return self._cancelled
+
+ def running(self):
+ with self._condition:
+ return not self._cancelled and not self._matured
+
+ def done(self):
+ with self._condition:
+ return self._cancelled or self._matured
+
+ def result(self, timeout=None):
+ self._block(timeout)
+ return None
+
+ def exception(self, timeout=None):
+ self._block(timeout)
+ return None
+
+ def traceback(self, timeout=None):
+ self._block(timeout)
+ return None
+
+ def add_done_callback(self, fn):
+ with self._condition:
+ if not self._cancelled and not self._matured:
+ self._done_callbacks.append(fn)
+ return
+
+ fn(self)
+
+ def start(self):
+ with self._condition:
+ self._channel.subscribe(self._update, try_to_connect=True)
+
+ def __del__(self):
+ with self._condition:
+ if not self._cancelled and not self._matured:
+ self._channel.unsubscribe(self._update)
+
+
+def channel_ready_future(channel):
+ """Creates a future.Future that matures when a beta.Channel is ready.
+
+ Cancelling the returned future.Future does not tell the given beta.Channel to
+ abandon attempts it may have been making to connect; cancelling merely
+ deactivates the return future.Future's subscription to the given
+ beta.Channel's connectivity.
+
+ Args:
+ channel: A beta.Channel.
+
+ Returns:
+ A future.Future that matures when the given Channel has connectivity
+ beta.ChannelConnectivity.READY.
+ """
+ ready_future = _ChannelReadyFuture(channel)
+ ready_future.start()
+ return ready_future
+
diff --git a/src/python/grpcio/grpc/framework/core/_context.py b/src/python/grpcio/grpc/framework/core/_context.py
index 24a12b612e..76b3534530 100644
--- a/src/python/grpcio/grpc/framework/core/_context.py
+++ b/src/python/grpcio/grpc/framework/core/_context.py
@@ -60,7 +60,7 @@ class OperationContext(base.OperationContext):
with self._lock:
if self._termination_manager.outcome is None:
self._termination_manager.abort(outcome)
- self._transmission_manager.abort(outcome)
+ self._transmission_manager.abort(outcome, None, None)
self._expiration_manager.terminate()
def outcome(self):
diff --git a/src/python/grpcio/grpc/framework/core/_emission.py b/src/python/grpcio/grpc/framework/core/_emission.py
index 7c702ab2ce..2d7b2e2f10 100644
--- a/src/python/grpcio/grpc/framework/core/_emission.py
+++ b/src/python/grpcio/grpc/framework/core/_emission.py
@@ -82,7 +82,8 @@ class EmissionManager(_interfaces.EmissionManager):
completion_present and self._completion_seen or
allowance_present and allowance <= 0):
self._termination_manager.abort(base.Outcome.LOCAL_FAILURE)
- self._transmission_manager.abort(base.Outcome.LOCAL_FAILURE)
+ self._transmission_manager.abort(
+ base.Outcome.LOCAL_FAILURE, None, None)
self._expiration_manager.terminate()
else:
self._initial_metadata_seen |= initial_metadata_present
diff --git a/src/python/grpcio/grpc/framework/core/_end.py b/src/python/grpcio/grpc/framework/core/_end.py
index fb2c532df6..5ef2f6d3a3 100644
--- a/src/python/grpcio/grpc/framework/core/_end.py
+++ b/src/python/grpcio/grpc/framework/core/_end.py
@@ -30,7 +30,6 @@
"""Implementation of base.End."""
import abc
-import enum
import threading
import uuid
@@ -75,7 +74,7 @@ def _abort(operations):
def _cancel_futures(futures):
for future in futures:
- futures.cancel()
+ future.cancel()
def _future_shutdown(lock, cycle, event):
@@ -83,8 +82,6 @@ def _future_shutdown(lock, cycle, event):
with lock:
_abort(cycle.operations.values())
_cancel_futures(cycle.futures)
- pool = cycle.pool
- cycle.pool.shutdown(wait=True)
return in_future
@@ -113,6 +110,7 @@ def _termination_action(lock, stats, operation_id, cycle):
cycle.idle_actions = []
if cycle.grace:
_cancel_futures(cycle.futures)
+ cycle.pool.shutdown(wait=False)
return termination_action
diff --git a/src/python/grpcio/grpc/framework/core/_expiration.py b/src/python/grpcio/grpc/framework/core/_expiration.py
index d94bdf2d2b..d8690b3a02 100644
--- a/src/python/grpcio/grpc/framework/core/_expiration.py
+++ b/src/python/grpcio/grpc/framework/core/_expiration.py
@@ -73,7 +73,7 @@ class _ExpirationManager(_interfaces.ExpirationManager):
if self._future is not None and index == self._index:
self._future = None
self._termination_manager.expire()
- self._transmission_manager.abort(base.Outcome.EXPIRED)
+ self._transmission_manager.abort(base.Outcome.EXPIRED, None, None)
return expire
def start(self):
diff --git a/src/python/grpcio/grpc/framework/core/_ingestion.py b/src/python/grpcio/grpc/framework/core/_ingestion.py
index 59f7f8adc8..7b8127f3fc 100644
--- a/src/python/grpcio/grpc/framework/core/_ingestion.py
+++ b/src/python/grpcio/grpc/framework/core/_ingestion.py
@@ -31,6 +31,7 @@
import abc
import collections
+import enum
from grpc.framework.core import _constants
from grpc.framework.core import _interfaces
@@ -42,21 +43,31 @@ _CREATE_SUBSCRIPTION_EXCEPTION_LOG_MESSAGE = 'Exception initializing ingestion!'
_INGESTION_EXCEPTION_LOG_MESSAGE = 'Exception during ingestion!'
-class _SubscriptionCreation(collections.namedtuple(
- '_SubscriptionCreation', ('subscription', 'remote_error', 'abandoned'))):
+class _SubscriptionCreation(
+ collections.namedtuple(
+ '_SubscriptionCreation',
+ ('kind', 'subscription', 'code', 'message',))):
"""A sum type for the outcome of ingestion initialization.
- Either subscription will be non-None, remote_error will be True, or abandoned
- will be True.
-
Attributes:
- subscription: A base.Subscription describing the customer's interest in
- operation values from the other side.
- remote_error: A boolean indicating that the subscription could not be
- created due to an error on the remote side of the operation.
- abandoned: A boolean indicating that subscription creation was abandoned.
+ kind: A Kind value coarsely indicating how subscription creation completed.
+ subscription: The created subscription. Only present if kind is
+ Kind.SUBSCRIPTION.
+ code: A code value to be sent to the other side of the operation along with
+ an indication that the operation is being aborted due to an error on the
+ remote side of the operation. Only present if kind is Kind.REMOTE_ERROR.
+ message: A message value to be sent to the other side of the operation
+ along with an indication that the operation is being aborted due to an
+ error on the remote side of the operation. Only present if kind is
+ Kind.REMOTE_ERROR.
"""
+ @enum.unique
+ class Kind(enum.Enum):
+ SUBSCRIPTION = 'subscription'
+ REMOTE_ERROR = 'remote error'
+ ABANDONED = 'abandoned'
+
class _SubscriptionCreator(object):
"""Common specification of subscription-creating behavior."""
@@ -101,12 +112,15 @@ class _ServiceSubscriptionCreator(_SubscriptionCreator):
try:
subscription = self._servicer.service(
group, method, self._operation_context, self._output_operator)
- except base.NoSuchMethodError:
- return _SubscriptionCreation(None, True, False)
+ except base.NoSuchMethodError as e:
+ return _SubscriptionCreation(
+ _SubscriptionCreation.Kind.REMOTE_ERROR, None, e.code, e.message)
except abandonment.Abandoned:
- return _SubscriptionCreation(None, False, True)
+ return _SubscriptionCreation(
+ _SubscriptionCreation.Kind.ABANDONED, None, None, None)
else:
- return _SubscriptionCreation(subscription, False, False)
+ return _SubscriptionCreation(
+ _SubscriptionCreation.Kind.SUBSCRIPTION, subscription, None, None)
def _wrap(behavior):
@@ -176,10 +190,10 @@ class _IngestionManager(_interfaces.IngestionManager):
self._pending_payloads = None
self._pending_completion = None
- def _abort_and_notify(self, outcome):
+ def _abort_and_notify(self, outcome, code, message):
self._abort_internal_only()
self._termination_manager.abort(outcome)
- self._transmission_manager.abort(outcome)
+ self._transmission_manager.abort(outcome, code, message)
self._expiration_manager.terminate()
def _operator_next(self):
@@ -236,12 +250,12 @@ class _IngestionManager(_interfaces.IngestionManager):
else:
with self._lock:
if self._termination_manager.outcome is None:
- self._abort_and_notify(base.Outcome.LOCAL_FAILURE)
+ self._abort_and_notify(base.Outcome.LOCAL_FAILURE, None, None)
return
else:
with self._lock:
if self._termination_manager.outcome is None:
- self._abort_and_notify(base.Outcome.LOCAL_FAILURE)
+ self._abort_and_notify(base.Outcome.LOCAL_FAILURE, None, None)
return
def _operator_post_create(self, subscription):
@@ -260,20 +274,22 @@ class _IngestionManager(_interfaces.IngestionManager):
def _create(self, subscription_creator, group, name):
outcome = callable_util.call_logging_exceptions(
- subscription_creator.create, _CREATE_SUBSCRIPTION_EXCEPTION_LOG_MESSAGE,
- group, name)
+ subscription_creator.create,
+ _CREATE_SUBSCRIPTION_EXCEPTION_LOG_MESSAGE, group, name)
if outcome.return_value is None:
with self._lock:
if self._termination_manager.outcome is None:
- self._abort_and_notify(base.Outcome.LOCAL_FAILURE)
- elif outcome.return_value.abandoned:
+ self._abort_and_notify(base.Outcome.LOCAL_FAILURE, None, None)
+ elif outcome.return_value.kind is _SubscriptionCreation.Kind.ABANDONED:
with self._lock:
if self._termination_manager.outcome is None:
- self._abort_and_notify(base.Outcome.LOCAL_FAILURE)
- elif outcome.return_value.remote_error:
+ self._abort_and_notify(base.Outcome.LOCAL_FAILURE, None, None)
+ elif outcome.return_value.kind is _SubscriptionCreation.Kind.REMOTE_ERROR:
+ code = outcome.return_value.code
+ message = outcome.return_value.message
with self._lock:
if self._termination_manager.outcome is None:
- self._abort_and_notify(base.Outcome.REMOTE_FAILURE)
+ self._abort_and_notify(base.Outcome.REMOTE_FAILURE, code, message)
elif outcome.return_value.subscription.kind is base.Subscription.Kind.FULL:
self._operator_post_create(outcome.return_value.subscription)
else:
diff --git a/src/python/grpcio/grpc/framework/core/_interfaces.py b/src/python/grpcio/grpc/framework/core/_interfaces.py
index a626b9f767..deb5f34f9b 100644
--- a/src/python/grpcio/grpc/framework/core/_interfaces.py
+++ b/src/python/grpcio/grpc/framework/core/_interfaces.py
@@ -155,13 +155,19 @@ class TransmissionManager(object):
raise NotImplementedError()
@abc.abstractmethod
- def abort(self, outcome):
+ def abort(self, outcome, code, message):
"""Indicates that the operation has aborted.
Args:
outcome: An interfaces.Outcome for the operation. If None, indicates that
the operation abortion should not be communicated to the other side of
the operation.
+ code: A code value to communicate to the other side of the operation
+ along with indication of operation abortion. May be None, and has no
+ effect if outcome is None.
+ message: A message value to communicate to the other side of the
+ operation along with indication of operation abortion. May be None, and
+ has no effect if outcome is None.
"""
raise NotImplementedError()
diff --git a/src/python/grpcio/grpc/framework/core/_operation.py b/src/python/grpcio/grpc/framework/core/_operation.py
index d20e40a53d..cc873c03f9 100644
--- a/src/python/grpcio/grpc/framework/core/_operation.py
+++ b/src/python/grpcio/grpc/framework/core/_operation.py
@@ -79,7 +79,7 @@ class _EasyOperation(_interfaces.Operation):
with self._lock:
if self._termination_manager.outcome is None:
self._termination_manager.abort(outcome)
- self._transmission_manager.abort(outcome)
+ self._transmission_manager.abort(outcome, None, None)
self._expiration_manager.terminate()
diff --git a/src/python/grpcio/grpc/framework/core/_reception.py b/src/python/grpcio/grpc/framework/core/_reception.py
index 0858f64ff6..1cebe3874b 100644
--- a/src/python/grpcio/grpc/framework/core/_reception.py
+++ b/src/python/grpcio/grpc/framework/core/_reception.py
@@ -73,7 +73,7 @@ class ReceptionManager(_interfaces.ReceptionManager):
self._aborted = True
if self._termination_manager.outcome is None:
self._termination_manager.abort(outcome)
- self._transmission_manager.abort(None)
+ self._transmission_manager.abort(None, None, None)
self._expiration_manager.terminate()
def _sequence_failure(self, ticket):
diff --git a/src/python/grpcio/grpc/framework/core/_transmission.py b/src/python/grpcio/grpc/framework/core/_transmission.py
index 03644f4d49..efef87dd4c 100644
--- a/src/python/grpcio/grpc/framework/core/_transmission.py
+++ b/src/python/grpcio/grpc/framework/core/_transmission.py
@@ -104,9 +104,13 @@ class TransmissionManager(_interfaces.TransmissionManager):
return None
else:
self._abortion_outcome = None
+ if self._completion is None:
+ code, message = None, None
+ else:
+ code, message = self._completion.code, self._completion.message
return links.Ticket(
self._operation_id, self._lowest_unused_sequence_number, None,
- None, None, None, None, None, None, None, None, None,
+ None, None, None, None, None, None, None, code, message,
termination, None)
action = False
@@ -277,7 +281,7 @@ class TransmissionManager(_interfaces.TransmissionManager):
self._remote_complete = True
self._local_allowance = 0
- def abort(self, outcome):
+ def abort(self, outcome, code, message):
"""See _interfaces.TransmissionManager.abort for specification."""
if self._transmitting:
self._aborted, self._abortion_outcome = True, outcome
@@ -287,8 +291,12 @@ class TransmissionManager(_interfaces.TransmissionManager):
termination = _constants.ABORTION_OUTCOME_TO_TICKET_TERMINATION[
outcome]
if termination is not None:
+ if self._completion is None:
+ code, message = None, None
+ else:
+ code, message = self._completion.code, self._completion.message
ticket = links.Ticket(
self._operation_id, self._lowest_unused_sequence_number, None,
- None, None, None, None, None, None, None, None, None,
+ None, None, None, None, None, None, None, code, message,
termination, None)
self._transmit(ticket)
diff --git a/src/python/grpcio/grpc/framework/crust/__init__.py b/src/python/grpcio/grpc/framework/crust/__init__.py
new file mode 100644
index 0000000000..7086519106
--- /dev/null
+++ b/src/python/grpcio/grpc/framework/crust/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
diff --git a/src/python/grpcio/grpc/framework/crust/_calls.py b/src/python/grpcio/grpc/framework/crust/_calls.py
new file mode 100644
index 0000000000..f9077bedfe
--- /dev/null
+++ b/src/python/grpcio/grpc/framework/crust/_calls.py
@@ -0,0 +1,204 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Utility functions for invoking RPCs."""
+
+from grpc.framework.crust import _control
+from grpc.framework.interfaces.base import utilities
+from grpc.framework.interfaces.face import face
+
+_ITERATOR_EXCEPTION_LOG_MESSAGE = 'Exception iterating over requests!'
+
+_EMPTY_COMPLETION = utilities.completion(None, None, None)
+
+
+def _invoke(end, group, method, timeout, initial_metadata, payload, complete):
+ rendezvous = _control.Rendezvous(None, None)
+ operation_context, operator = end.operate(
+ group, method, utilities.full_subscription(rendezvous), timeout,
+ initial_metadata=initial_metadata, payload=payload,
+ completion=_EMPTY_COMPLETION if complete else None)
+ rendezvous.set_operator_and_context(operator, operation_context)
+ outcome = operation_context.add_termination_callback(rendezvous.set_outcome)
+ if outcome is not None:
+ rendezvous.set_outcome(outcome)
+ return rendezvous, operation_context, outcome
+
+
+def _event_return_unary(
+ receiver, abortion_callback, rendezvous, operation_context, outcome, pool):
+ if outcome is None:
+ def in_pool():
+ abortion = rendezvous.add_abortion_callback(abortion_callback)
+ if abortion is None:
+ try:
+ receiver.initial_metadata(rendezvous.initial_metadata())
+ receiver.response(next(rendezvous))
+ receiver.complete(
+ rendezvous.terminal_metadata(), rendezvous.code(),
+ rendezvous.details())
+ except face.AbortionError:
+ pass
+ else:
+ abortion_callback(abortion)
+ pool.submit(_control.pool_wrap(in_pool, operation_context))
+ return rendezvous
+
+
+def _event_return_stream(
+ receiver, abortion_callback, rendezvous, operation_context, outcome, pool):
+ if outcome is None:
+ def in_pool():
+ abortion = rendezvous.add_abortion_callback(abortion_callback)
+ if abortion is None:
+ try:
+ receiver.initial_metadata(rendezvous.initial_metadata())
+ for response in rendezvous:
+ receiver.response(response)
+ receiver.complete(
+ rendezvous.terminal_metadata(), rendezvous.code(),
+ rendezvous.details())
+ except face.AbortionError:
+ pass
+ else:
+ abortion_callback(abortion)
+ pool.submit(_control.pool_wrap(in_pool, operation_context))
+ return rendezvous
+
+
+def blocking_unary_unary(
+ end, group, method, timeout, with_call, initial_metadata, payload):
+ """Services in a blocking fashion a unary-unary servicer method."""
+ rendezvous, unused_operation_context, unused_outcome = _invoke(
+ end, group, method, timeout, initial_metadata, payload, True)
+ if with_call:
+ return next(rendezvous, rendezvous)
+ else:
+ return next(rendezvous)
+
+
+def future_unary_unary(end, group, method, timeout, initial_metadata, payload):
+ """Services a value-in value-out servicer method by returning a Future."""
+ rendezvous, unused_operation_context, unused_outcome = _invoke(
+ end, group, method, timeout, initial_metadata, payload, True)
+ return rendezvous
+
+
+def inline_unary_stream(end, group, method, timeout, initial_metadata, payload):
+ """Services a value-in stream-out servicer method."""
+ rendezvous, unused_operation_context, unused_outcome = _invoke(
+ end, group, method, timeout, initial_metadata, payload, True)
+ return rendezvous
+
+
+def blocking_stream_unary(
+ end, group, method, timeout, with_call, initial_metadata, payload_iterator,
+ pool):
+ """Services in a blocking fashion a stream-in value-out servicer method."""
+ rendezvous, operation_context, outcome = _invoke(
+ end, group, method, timeout, initial_metadata, None, False)
+ if outcome is None:
+ def in_pool():
+ for payload in payload_iterator:
+ rendezvous.consume(payload)
+ rendezvous.terminate()
+ pool.submit(_control.pool_wrap(in_pool, operation_context))
+ if with_call:
+ return next(rendezvous), rendezvous
+ else:
+ return next(rendezvous)
+ else:
+ if with_call:
+ return next(rendezvous), rendezvous
+ else:
+ return next(rendezvous)
+
+
+def future_stream_unary(
+ end, group, method, timeout, initial_metadata, payload_iterator, pool):
+ """Services a stream-in value-out servicer method by returning a Future."""
+ rendezvous, operation_context, outcome = _invoke(
+ end, group, method, timeout, initial_metadata, None, False)
+ if outcome is None:
+ def in_pool():
+ for payload in payload_iterator:
+ rendezvous.consume(payload)
+ rendezvous.terminate()
+ pool.submit(_control.pool_wrap(in_pool, operation_context))
+ return rendezvous
+
+
+def inline_stream_stream(
+ end, group, method, timeout, initial_metadata, payload_iterator, pool):
+ """Services a stream-in stream-out servicer method."""
+ rendezvous, operation_context, outcome = _invoke(
+ end, group, method, timeout, initial_metadata, None, False)
+ if outcome is None:
+ def in_pool():
+ for payload in payload_iterator:
+ rendezvous.consume(payload)
+ rendezvous.terminate()
+ pool.submit(_control.pool_wrap(in_pool, operation_context))
+ return rendezvous
+
+
+def event_unary_unary(
+ end, group, method, timeout, initial_metadata, payload, receiver,
+ abortion_callback, pool):
+ rendezvous, operation_context, outcome = _invoke(
+ end, group, method, timeout, initial_metadata, payload, True)
+ return _event_return_unary(
+ receiver, abortion_callback, rendezvous, operation_context, outcome, pool)
+
+
+def event_unary_stream(
+ end, group, method, timeout, initial_metadata, payload,
+ receiver, abortion_callback, pool):
+ rendezvous, operation_context, outcome = _invoke(
+ end, group, method, timeout, initial_metadata, payload, True)
+ return _event_return_stream(
+ receiver, abortion_callback, rendezvous, operation_context, outcome, pool)
+
+
+def event_stream_unary(
+ end, group, method, timeout, initial_metadata, receiver, abortion_callback,
+ pool):
+ rendezvous, operation_context, outcome = _invoke(
+ end, group, method, timeout, initial_metadata, None, False)
+ return _event_return_unary(
+ receiver, abortion_callback, rendezvous, operation_context, outcome, pool)
+
+
+def event_stream_stream(
+ end, group, method, timeout, initial_metadata, receiver, abortion_callback,
+ pool):
+ rendezvous, operation_context, outcome = _invoke(
+ end, group, method, timeout, initial_metadata, None, False)
+ return _event_return_stream(
+ receiver, abortion_callback, rendezvous, operation_context, outcome, pool)
diff --git a/src/python/grpcio/grpc/framework/crust/_control.py b/src/python/grpcio/grpc/framework/crust/_control.py
new file mode 100644
index 0000000000..01de3c15bd
--- /dev/null
+++ b/src/python/grpcio/grpc/framework/crust/_control.py
@@ -0,0 +1,545 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""State and behavior for translating between sync and async control flow."""
+
+import collections
+import enum
+import sys
+import threading
+import time
+
+from grpc.framework.foundation import abandonment
+from grpc.framework.foundation import callable_util
+from grpc.framework.foundation import future
+from grpc.framework.foundation import stream
+from grpc.framework.interfaces.base import base
+from grpc.framework.interfaces.base import utilities
+from grpc.framework.interfaces.face import face
+
+_DONE_CALLBACK_LOG_MESSAGE = 'Exception calling Future "done" callback!'
+_INTERNAL_ERROR_LOG_MESSAGE = ':-( RPC Framework (Crust) Internal Error! )-:'
+
+_CANNOT_SET_INITIAL_METADATA = (
+ 'Could not set initial metadata - has it already been set, or has a ' +
+ 'payload already been sent?')
+_CANNOT_SET_TERMINAL_METADATA = (
+ 'Could not set terminal metadata - has it already been set, or has RPC ' +
+ 'completion already been indicated?')
+_CANNOT_SET_CODE = (
+ 'Could not set code - has it already been set, or has RPC completion ' +
+ 'already been indicated?')
+_CANNOT_SET_DETAILS = (
+ 'Could not set details - has it already been set, or has RPC completion ' +
+ 'already been indicated?')
+
+
+class _DummyOperator(base.Operator):
+
+ def advance(
+ self, initial_metadata=None, payload=None, completion=None,
+ allowance=None):
+ pass
+
+_DUMMY_OPERATOR = _DummyOperator()
+
+
+class _Awaited(
+ collections.namedtuple('_Awaited', ('kind', 'value',))):
+
+ @enum.unique
+ class Kind(enum.Enum):
+ NOT_YET_ARRIVED = 'not yet arrived'
+ ARRIVED = 'arrived'
+
+_NOT_YET_ARRIVED = _Awaited(_Awaited.Kind.NOT_YET_ARRIVED, None)
+_ARRIVED_AND_NONE = _Awaited(_Awaited.Kind.ARRIVED, None)
+
+
+class _Transitory(
+ collections.namedtuple('_Transitory', ('kind', 'value',))):
+
+ @enum.unique
+ class Kind(enum.Enum):
+ NOT_YET_SEEN = 'not yet seen'
+ PRESENT = 'present'
+ GONE = 'gone'
+
+_NOT_YET_SEEN = _Transitory(_Transitory.Kind.NOT_YET_SEEN, None)
+_GONE = _Transitory(_Transitory.Kind.GONE, None)
+
+
+class _Termination(
+ collections.namedtuple(
+ '_Termination', ('terminated', 'abortion', 'abortion_error',))):
+ """Values indicating whether and how an RPC has terminated.
+
+ Attributes:
+ terminated: A boolean indicating whether or not the RPC has terminated.
+ abortion: A face.Abortion value describing the RPC's abortion or None if the
+ RPC did not abort.
+ abortion_error: A face.AbortionError describing the RPC's abortion or None
+ if the RPC did not abort.
+ """
+
+_NOT_TERMINATED = _Termination(False, None, None)
+
+_OPERATION_OUTCOME_TO_TERMINATION_CONSTRUCTOR = {
+ base.Outcome.COMPLETED: lambda *unused_args: _Termination(True, None, None),
+ base.Outcome.CANCELLED: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.CANCELLED, *args),
+ face.CancellationError(*args)),
+ base.Outcome.EXPIRED: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.EXPIRED, *args),
+ face.ExpirationError(*args)),
+ base.Outcome.LOCAL_SHUTDOWN: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.LOCAL_SHUTDOWN, *args),
+ face.LocalShutdownError(*args)),
+ base.Outcome.REMOTE_SHUTDOWN: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.REMOTE_SHUTDOWN, *args),
+ face.RemoteShutdownError(*args)),
+ base.Outcome.RECEPTION_FAILURE: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.NETWORK_FAILURE, *args),
+ face.NetworkError(*args)),
+ base.Outcome.TRANSMISSION_FAILURE: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.NETWORK_FAILURE, *args),
+ face.NetworkError(*args)),
+ base.Outcome.LOCAL_FAILURE: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.LOCAL_FAILURE, *args),
+ face.LocalError(*args)),
+ base.Outcome.REMOTE_FAILURE: lambda *args: _Termination(
+ True, face.Abortion(face.Abortion.Kind.REMOTE_FAILURE, *args),
+ face.RemoteError(*args)),
+}
+
+
+def _wait_once_until(condition, until):
+ if until is None:
+ condition.wait()
+ else:
+ remaining = until - time.time()
+ if remaining < 0:
+ raise future.TimeoutError()
+ else:
+ condition.wait(timeout=remaining)
+
+
+def _done_callback_as_operation_termination_callback(
+ done_callback, rendezvous):
+ def operation_termination_callback(operation_outcome):
+ rendezvous.set_outcome(operation_outcome)
+ done_callback(rendezvous)
+ return operation_termination_callback
+
+
+def _abortion_callback_as_operation_termination_callback(
+ rpc_abortion_callback, rendezvous_set_outcome):
+ def operation_termination_callback(operation_outcome):
+ termination = rendezvous_set_outcome(operation_outcome)
+ if termination.abortion is not None:
+ rpc_abortion_callback(termination.abortion)
+ return operation_termination_callback
+
+
+class Rendezvous(base.Operator, future.Future, stream.Consumer, face.Call):
+ """A rendez-vous for the threads of an operation.
+
+ Instances of this object present iterator and stream.Consumer interfaces for
+ interacting with application code and present a base.Operator interface and
+ maintain a base.Operator internally for interacting with base interface code.
+ """
+
+ def __init__(self, operator, operation_context):
+ self._condition = threading.Condition()
+
+ self._operator = operator
+ self._operation_context = operation_context
+
+ self._up_initial_metadata = _NOT_YET_ARRIVED
+ self._up_payload = None
+ self._up_allowance = 1
+ self._up_completion = _NOT_YET_ARRIVED
+ self._down_initial_metadata = _NOT_YET_SEEN
+ self._down_payload = None
+ self._down_allowance = 1
+ self._down_terminal_metadata = _NOT_YET_SEEN
+ self._down_code = _NOT_YET_SEEN
+ self._down_details = _NOT_YET_SEEN
+
+ self._termination = _NOT_TERMINATED
+
+ # The semantics of future.Future.cancel and future.Future.cancelled are
+ # slightly wonky, so they have to be tracked separately from the rest of the
+ # result of the RPC. This field tracks whether cancellation was requested
+ # prior to termination of the RPC
+ self._cancelled = False
+
+ def set_operator_and_context(self, operator, operation_context):
+ with self._condition:
+ self._operator = operator
+ self._operation_context = operation_context
+
+ def _down_completion(self):
+ if self._down_terminal_metadata.kind is _Transitory.Kind.NOT_YET_SEEN:
+ terminal_metadata = None
+ self._down_terminal_metadata = _GONE
+ elif self._down_terminal_metadata.kind is _Transitory.Kind.PRESENT:
+ terminal_metadata = self._down_terminal_metadata.value
+ self._down_terminal_metadata = _GONE
+ else:
+ terminal_metadata = None
+ if self._down_code.kind is _Transitory.Kind.NOT_YET_SEEN:
+ code = None
+ self._down_code = _GONE
+ elif self._down_code.kind is _Transitory.Kind.PRESENT:
+ code = self._down_code.value
+ self._down_code = _GONE
+ else:
+ code = None
+ if self._down_details.kind is _Transitory.Kind.NOT_YET_SEEN:
+ details = None
+ self._down_details = _GONE
+ elif self._down_details.kind is _Transitory.Kind.PRESENT:
+ details = self._down_details.value
+ self._down_details = _GONE
+ else:
+ details = None
+ return utilities.completion(terminal_metadata, code, details)
+
+ def _set_outcome(self, outcome):
+ if not self._termination.terminated:
+ self._operator = _DUMMY_OPERATOR
+ self._operation_context = None
+ self._down_initial_metadata = _GONE
+ self._down_payload = None
+ self._down_terminal_metadata = _GONE
+ self._down_code = _GONE
+ self._down_details = _GONE
+
+ if self._up_initial_metadata.kind is _Awaited.Kind.NOT_YET_ARRIVED:
+ initial_metadata = None
+ else:
+ initial_metadata = self._up_initial_metadata.value
+ if self._up_completion.kind is _Awaited.Kind.NOT_YET_ARRIVED:
+ terminal_metadata, code, details = None, None, None
+ else:
+ terminal_metadata = self._up_completion.value.terminal_metadata
+ code = self._up_completion.value.code
+ details = self._up_completion.value.message
+ self._termination = _OPERATION_OUTCOME_TO_TERMINATION_CONSTRUCTOR[
+ outcome](initial_metadata, terminal_metadata, code, details)
+
+ self._condition.notify_all()
+
+ return self._termination
+
+ def advance(
+ self, initial_metadata=None, payload=None, completion=None,
+ allowance=None):
+ with self._condition:
+ if initial_metadata is not None:
+ self._up_initial_metadata = _Awaited(
+ _Awaited.Kind.ARRIVED, initial_metadata)
+ if payload is not None:
+ if self._up_initial_metadata.kind is _Awaited.Kind.NOT_YET_ARRIVED:
+ self._up_initial_metadata = _ARRIVED_AND_NONE
+ self._up_payload = payload
+ self._up_allowance -= 1
+ if completion is not None:
+ if self._up_initial_metadata.kind is _Awaited.Kind.NOT_YET_ARRIVED:
+ self._up_initial_metadata = _ARRIVED_AND_NONE
+ self._up_completion = _Awaited(
+ _Awaited.Kind.ARRIVED, completion)
+ if allowance is not None:
+ if self._down_payload is not None:
+ self._operator.advance(payload=self._down_payload)
+ self._down_payload = None
+ self._down_allowance += allowance - 1
+ else:
+ self._down_allowance += allowance
+ self._condition.notify_all()
+
+ def cancel(self):
+ with self._condition:
+ if self._operation_context is not None:
+ self._operation_context.cancel()
+ self._cancelled = True
+ return False
+
+ def cancelled(self):
+ with self._condition:
+ return self._cancelled
+
+ def running(self):
+ with self._condition:
+ return not self._termination.terminated
+
+ def done(self):
+ with self._condition:
+ return self._termination.terminated
+
+ def result(self, timeout=None):
+ until = None if timeout is None else time.time() + timeout
+ with self._condition:
+ while True:
+ if self._termination.terminated:
+ if self._termination.abortion is None:
+ return self._up_payload
+ elif self._termination.abortion.kind is face.Abortion.Kind.CANCELLED:
+ raise future.CancelledError()
+ else:
+ raise self._termination.abortion_error # pylint: disable=raising-bad-type
+ else:
+ _wait_once_until(self._condition, until)
+
+ def exception(self, timeout=None):
+ until = None if timeout is None else time.time() + timeout
+ with self._condition:
+ while True:
+ if self._termination.terminated:
+ if self._termination.abortion is None:
+ return None
+ else:
+ return self._termination.abortion_error
+ else:
+ _wait_once_until(self._condition, until)
+
+ def traceback(self, timeout=None):
+ until = None if timeout is None else time.time() + timeout
+ with self._condition:
+ while True:
+ if self._termination.terminated:
+ if self._termination.abortion_error is None:
+ return None
+ else:
+ abortion_error = self._termination.abortion_error
+ break
+ else:
+ _wait_once_until(self._condition, until)
+
+ try:
+ raise abortion_error
+ except face.AbortionError:
+ return sys.exc_info()[2]
+
+ def add_done_callback(self, fn):
+ with self._condition:
+ if self._operation_context is not None:
+ outcome = self._operation_context.add_termination_callback(
+ _done_callback_as_operation_termination_callback(fn, self))
+ if outcome is None:
+ return
+ else:
+ self._set_outcome(outcome)
+
+ fn(self)
+
+ def consume(self, value):
+ with self._condition:
+ while True:
+ if self._termination.terminated:
+ return
+ elif 0 < self._down_allowance:
+ self._operator.advance(payload=value)
+ self._down_allowance -= 1
+ return
+ else:
+ self._condition.wait()
+
+ def terminate(self):
+ with self._condition:
+ if self._termination.terminated:
+ return
+ elif self._down_code.kind is _Transitory.Kind.GONE:
+ # Conform to specified idempotence of terminate by ignoring extra calls.
+ return
+ else:
+ completion = self._down_completion()
+ self._operator.advance(completion=completion)
+
+ def consume_and_terminate(self, value):
+ with self._condition:
+ while True:
+ if self._termination.terminated:
+ return
+ elif 0 < self._down_allowance:
+ completion = self._down_completion()
+ self._operator.advance(payload=value, completion=completion)
+ return
+ else:
+ self._condition.wait()
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ with self._condition:
+ while True:
+ if self._termination.abortion_error is not None:
+ raise self._termination.abortion_error
+ elif self._up_payload is not None:
+ payload = self._up_payload
+ self._up_payload = None
+ if self._up_completion.kind is _Awaited.Kind.NOT_YET_ARRIVED:
+ self._operator.advance(allowance=1)
+ return payload
+ elif self._up_completion.kind is _Awaited.Kind.ARRIVED:
+ raise StopIteration()
+ else:
+ self._condition.wait()
+
+ def is_active(self):
+ with self._condition:
+ return not self._termination.terminated
+
+ def time_remaining(self):
+ if self._operation_context is None:
+ return 0
+ else:
+ return self._operation_context.time_remaining()
+
+ def add_abortion_callback(self, abortion_callback):
+ with self._condition:
+ if self._operation_context is None:
+ return self._termination.abortion
+ else:
+ outcome = self._operation_context.add_termination_callback(
+ _abortion_callback_as_operation_termination_callback(
+ abortion_callback, self.set_outcome))
+ if outcome is not None:
+ return self._set_outcome(outcome).abortion
+ else:
+ return self._termination.abortion
+
+ def initial_metadata(self):
+ with self._condition:
+ while True:
+ if self._up_initial_metadata.kind is _Awaited.Kind.ARRIVED:
+ return self._up_initial_metadata.value
+ elif self._termination.terminated:
+ return None
+ else:
+ self._condition.wait()
+
+ def terminal_metadata(self):
+ with self._condition:
+ while True:
+ if self._up_completion.kind is _Awaited.Kind.ARRIVED:
+ return self._up_completion.value.terminal_metadata
+ elif self._termination.terminated:
+ return None
+ else:
+ self._condition.wait()
+
+ def code(self):
+ with self._condition:
+ while True:
+ if self._up_completion.kind is _Awaited.Kind.ARRIVED:
+ return self._up_completion.value.code
+ elif self._termination.terminated:
+ return None
+ else:
+ self._condition.wait()
+
+ def details(self):
+ with self._condition:
+ while True:
+ if self._up_completion.kind is _Awaited.Kind.ARRIVED:
+ return self._up_completion.value.message
+ elif self._termination.terminated:
+ return None
+ else:
+ self._condition.wait()
+
+ def set_initial_metadata(self, initial_metadata):
+ with self._condition:
+ if (self._down_initial_metadata.kind is not
+ _Transitory.Kind.NOT_YET_SEEN):
+ raise ValueError(_CANNOT_SET_INITIAL_METADATA)
+ else:
+ self._down_initial_metadata = _GONE
+ self._operator.advance(initial_metadata=initial_metadata)
+
+ def set_terminal_metadata(self, terminal_metadata):
+ with self._condition:
+ if (self._down_terminal_metadata.kind is not
+ _Transitory.Kind.NOT_YET_SEEN):
+ raise ValueError(_CANNOT_SET_TERMINAL_METADATA)
+ else:
+ self._down_terminal_metadata = _Transitory(
+ _Transitory.Kind.PRESENT, terminal_metadata)
+
+ def set_code(self, code):
+ with self._condition:
+ if self._down_code.kind is not _Transitory.Kind.NOT_YET_SEEN:
+ raise ValueError(_CANNOT_SET_CODE)
+ else:
+ self._down_code = _Transitory(_Transitory.Kind.PRESENT, code)
+
+ def set_details(self, details):
+ with self._condition:
+ if self._down_details.kind is not _Transitory.Kind.NOT_YET_SEEN:
+ raise ValueError(_CANNOT_SET_DETAILS)
+ else:
+ self._down_details = _Transitory(_Transitory.Kind.PRESENT, details)
+
+ def set_outcome(self, outcome):
+ with self._condition:
+ return self._set_outcome(outcome)
+
+
+def pool_wrap(behavior, operation_context):
+ """Wraps an operation-related behavior so that it may be called in a pool.
+
+ Args:
+ behavior: A callable related to carrying out an operation.
+ operation_context: A base_interfaces.OperationContext for the operation.
+
+ Returns:
+ A callable that when called carries out the behavior of the given callable
+ and handles whatever exceptions it raises appropriately.
+ """
+ def translation(*args):
+ try:
+ behavior(*args)
+ except (
+ abandonment.Abandoned,
+ face.CancellationError,
+ face.ExpirationError,
+ face.LocalShutdownError,
+ face.RemoteShutdownError,
+ face.NetworkError,
+ face.RemoteError,
+ ) as e:
+ if operation_context.outcome() is None:
+ operation_context.fail(e)
+ except Exception as e:
+ operation_context.fail(e)
+ return callable_util.with_exceptions_logged(
+ translation, _INTERNAL_ERROR_LOG_MESSAGE)
diff --git a/src/python/grpcio/grpc/framework/crust/_service.py b/src/python/grpcio/grpc/framework/crust/_service.py
new file mode 100644
index 0000000000..2455a58f59
--- /dev/null
+++ b/src/python/grpcio/grpc/framework/crust/_service.py
@@ -0,0 +1,166 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Behaviors for servicing RPCs."""
+
+from grpc.framework.crust import _control
+from grpc.framework.foundation import abandonment
+from grpc.framework.interfaces.base import utilities
+from grpc.framework.interfaces.face import face
+
+
+class _ServicerContext(face.ServicerContext):
+
+ def __init__(self, rendezvous):
+ self._rendezvous = rendezvous
+
+ def is_active(self):
+ return self._rendezvous.is_active()
+
+ def time_remaining(self):
+ return self._rendezvous.time_remaining()
+
+ def add_abortion_callback(self, abortion_callback):
+ return self._rendezvous.add_abortion_callback(abortion_callback)
+
+ def cancel(self):
+ self._rendezvous.cancel()
+
+ def invocation_metadata(self):
+ return self._rendezvous.initial_metadata()
+
+ def initial_metadata(self, initial_metadata):
+ self._rendezvous.set_initial_metadata(initial_metadata)
+
+ def terminal_metadata(self, terminal_metadata):
+ self._rendezvous.set_terminal_metadata(terminal_metadata)
+
+ def code(self, code):
+ self._rendezvous.set_code(code)
+
+ def details(self, details):
+ self._rendezvous.set_details(details)
+
+
+def _adaptation(pool, in_pool):
+ def adaptation(operator, operation_context):
+ rendezvous = _control.Rendezvous(operator, operation_context)
+ outcome = operation_context.add_termination_callback(rendezvous.set_outcome)
+ if outcome is None:
+ pool.submit(_control.pool_wrap(in_pool, operation_context), rendezvous)
+ return utilities.full_subscription(rendezvous)
+ else:
+ raise abandonment.Abandoned()
+ return adaptation
+
+
+def adapt_inline_unary_unary(method, pool):
+ def in_pool(rendezvous):
+ request = next(rendezvous)
+ response = method(request, _ServicerContext(rendezvous))
+ rendezvous.consume_and_terminate(response)
+ return _adaptation(pool, in_pool)
+
+
+def adapt_inline_unary_stream(method, pool):
+ def in_pool(rendezvous):
+ request = next(rendezvous)
+ response_iterator = method(request, _ServicerContext(rendezvous))
+ for response in response_iterator:
+ rendezvous.consume(response)
+ rendezvous.terminate()
+ return _adaptation(pool, in_pool)
+
+
+def adapt_inline_stream_unary(method, pool):
+ def in_pool(rendezvous):
+ response = method(rendezvous, _ServicerContext(rendezvous))
+ rendezvous.consume_and_terminate(response)
+ return _adaptation(pool, in_pool)
+
+
+def adapt_inline_stream_stream(method, pool):
+ def in_pool(rendezvous):
+ response_iterator = method(rendezvous, _ServicerContext(rendezvous))
+ for response in response_iterator:
+ rendezvous.consume(response)
+ rendezvous.terminate()
+ return _adaptation(pool, in_pool)
+
+
+def adapt_event_unary_unary(method, pool):
+ def in_pool(rendezvous):
+ request = next(rendezvous)
+ method(
+ request, rendezvous.consume_and_terminate, _ServicerContext(rendezvous))
+ return _adaptation(pool, in_pool)
+
+
+def adapt_event_unary_stream(method, pool):
+ def in_pool(rendezvous):
+ request = next(rendezvous)
+ method(request, rendezvous, _ServicerContext(rendezvous))
+ return _adaptation(pool, in_pool)
+
+
+def adapt_event_stream_unary(method, pool):
+ def in_pool(rendezvous):
+ request_consumer = method(
+ rendezvous.consume_and_terminate, _ServicerContext(rendezvous))
+ for request in rendezvous:
+ request_consumer.consume(request)
+ request_consumer.terminate()
+ return _adaptation(pool, in_pool)
+
+
+def adapt_event_stream_stream(method, pool):
+ def in_pool(rendezvous):
+ request_consumer = method(rendezvous, _ServicerContext(rendezvous))
+ for request in rendezvous:
+ request_consumer.consume(request)
+ request_consumer.terminate()
+ return _adaptation(pool, in_pool)
+
+
+def adapt_multi_method(multi_method, pool):
+ def adaptation(group, method, operator, operation_context):
+ rendezvous = _control.Rendezvous(operator, operation_context)
+ outcome = operation_context.add_termination_callback(rendezvous.set_outcome)
+ if outcome is None:
+ def in_pool():
+ request_consumer = multi_method(
+ group, method, rendezvous, _ServicerContext(rendezvous))
+ for request in rendezvous:
+ request_consumer.consume(request)
+ request_consumer.terminate()
+ pool.submit(_control.pool_wrap(in_pool, operation_context), rendezvous)
+ return utilities.full_subscription(rendezvous)
+ else:
+ raise abandonment.Abandoned()
+ return adaptation
diff --git a/src/python/grpcio/grpc/framework/crust/implementations.py b/src/python/grpcio/grpc/framework/crust/implementations.py
new file mode 100644
index 0000000000..12f7e79641
--- /dev/null
+++ b/src/python/grpcio/grpc/framework/crust/implementations.py
@@ -0,0 +1,352 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Entry points into the Crust layer of RPC Framework."""
+
+from grpc.framework.common import cardinality
+from grpc.framework.common import style
+from grpc.framework.crust import _calls
+from grpc.framework.crust import _service
+from grpc.framework.interfaces.base import base
+from grpc.framework.interfaces.face import face
+
+
+class _BaseServicer(base.Servicer):
+
+ def __init__(self, adapted_methods, adapted_multi_method):
+ self._adapted_methods = adapted_methods
+ self._adapted_multi_method = adapted_multi_method
+
+ def service(self, group, method, context, output_operator):
+ adapted_method = self._adapted_methods.get((group, method), None)
+ if adapted_method is not None:
+ return adapted_method(output_operator, context)
+ elif self._adapted_multi_method is not None:
+ try:
+ return self._adapted_multi_method.service(
+ group, method, output_operator, context)
+ except face.NoSuchMethodError:
+ raise base.NoSuchMethodError()
+ else:
+ raise base.NoSuchMethodError()
+
+
+class _UnaryUnaryMultiCallable(face.UnaryUnaryMultiCallable):
+
+ def __init__(self, end, group, method, pool):
+ self._end = end
+ self._group = group
+ self._method = method
+ self._pool = pool
+
+ def __call__(
+ self, request, timeout, metadata=None, with_call=False):
+ return _calls.blocking_unary_unary(
+ self._end, self._group, self._method, timeout, with_call,
+ metadata, request)
+
+ def future(self, request, timeout, metadata=None):
+ return _calls.future_unary_unary(
+ self._end, self._group, self._method, timeout, metadata,
+ request)
+
+ def event(
+ self, request, receiver, abortion_callback, timeout,
+ metadata=None):
+ return _calls.event_unary_unary(
+ self._end, self._group, self._method, timeout, metadata,
+ request, receiver, abortion_callback, self._pool)
+
+
+class _UnaryStreamMultiCallable(face.UnaryStreamMultiCallable):
+
+ def __init__(self, end, group, method, pool):
+ self._end = end
+ self._group = group
+ self._method = method
+ self._pool = pool
+
+ def __call__(self, request, timeout, metadata=None):
+ return _calls.inline_unary_stream(
+ self._end, self._group, self._method, timeout, metadata,
+ request)
+
+ def event(
+ self, request, receiver, abortion_callback, timeout,
+ metadata=None):
+ return _calls.event_unary_stream(
+ self._end, self._group, self._method, timeout, metadata,
+ request, receiver, abortion_callback, self._pool)
+
+
+class _StreamUnaryMultiCallable(face.StreamUnaryMultiCallable):
+
+ def __init__(self, end, group, method, pool):
+ self._end = end
+ self._group = group
+ self._method = method
+ self._pool = pool
+
+ def __call__(
+ self, request_iterator, timeout, metadata=None,
+ with_call=False):
+ return _calls.blocking_stream_unary(
+ self._end, self._group, self._method, timeout, with_call,
+ metadata, request_iterator, self._pool)
+
+ def future(self, request_iterator, timeout, metadata=None):
+ return _calls.future_stream_unary(
+ self._end, self._group, self._method, timeout, metadata,
+ request_iterator, self._pool)
+
+ def event(
+ self, receiver, abortion_callback, timeout, metadata=None):
+ return _calls.event_stream_unary(
+ self._end, self._group, self._method, timeout, metadata,
+ receiver, abortion_callback, self._pool)
+
+
+class _StreamStreamMultiCallable(face.StreamStreamMultiCallable):
+
+ def __init__(self, end, group, method, pool):
+ self._end = end
+ self._group = group
+ self._method = method
+ self._pool = pool
+
+ def __call__(self, request_iterator, timeout, metadata=None):
+ return _calls.inline_stream_stream(
+ self._end, self._group, self._method, timeout, metadata,
+ request_iterator, self._pool)
+
+ def event(
+ self, receiver, abortion_callback, timeout, metadata=None):
+ return _calls.event_stream_stream(
+ self._end, self._group, self._method, timeout, metadata,
+ receiver, abortion_callback, self._pool)
+
+
+class _GenericStub(face.GenericStub):
+ """An face.GenericStub implementation."""
+
+ def __init__(self, end, pool):
+ self._end = end
+ self._pool = pool
+
+ def blocking_unary_unary(
+ self, group, method, request, timeout, metadata=None,
+ with_call=None):
+ return _calls.blocking_unary_unary(
+ self._end, group, method, timeout, with_call, metadata,
+ request)
+
+ def future_unary_unary(
+ self, group, method, request, timeout, metadata=None):
+ return _calls.future_unary_unary(
+ self._end, group, method, timeout, metadata, request)
+
+ def inline_unary_stream(
+ self, group, method, request, timeout, metadata=None):
+ return _calls.inline_unary_stream(
+ self._end, group, method, timeout, metadata, request)
+
+ def blocking_stream_unary(
+ self, group, method, request_iterator, timeout, metadata=None,
+ with_call=None):
+ return _calls.blocking_stream_unary(
+ self._end, group, method, timeout, with_call, metadata,
+ request_iterator, self._pool)
+
+ def future_stream_unary(
+ self, group, method, request_iterator, timeout, metadata=None):
+ return _calls.future_stream_unary(
+ self._end, group, method, timeout, metadata,
+ request_iterator, self._pool)
+
+ def inline_stream_stream(
+ self, group, method, request_iterator, timeout, metadata=None):
+ return _calls.inline_stream_stream(
+ self._end, group, method, timeout, metadata,
+ request_iterator, self._pool)
+
+ def event_unary_unary(
+ self, group, method, request, receiver, abortion_callback, timeout,
+ metadata=None):
+ return _calls.event_unary_unary(
+ self._end, group, method, timeout, metadata, request,
+ receiver, abortion_callback, self._pool)
+
+ def event_unary_stream(
+ self, group, method, request, receiver, abortion_callback, timeout,
+ metadata=None):
+ return _calls.event_unary_stream(
+ self._end, group, method, timeout, metadata, request,
+ receiver, abortion_callback, self._pool)
+
+ def event_stream_unary(
+ self, group, method, receiver, abortion_callback, timeout,
+ metadata=None):
+ return _calls.event_stream_unary(
+ self._end, group, method, timeout, metadata, receiver,
+ abortion_callback, self._pool)
+
+ def event_stream_stream(
+ self, group, method, receiver, abortion_callback, timeout,
+ metadata=None):
+ return _calls.event_stream_stream(
+ self._end, group, method, timeout, metadata, receiver,
+ abortion_callback, self._pool)
+
+ def unary_unary(self, group, method):
+ return _UnaryUnaryMultiCallable(self._end, group, method, self._pool)
+
+ def unary_stream(self, group, method):
+ return _UnaryStreamMultiCallable(self._end, group, method, self._pool)
+
+ def stream_unary(self, group, method):
+ return _StreamUnaryMultiCallable(self._end, group, method, self._pool)
+
+ def stream_stream(self, group, method):
+ return _StreamStreamMultiCallable(self._end, group, method, self._pool)
+
+
+class _DynamicStub(face.DynamicStub):
+ """An face.DynamicStub implementation."""
+
+ def __init__(self, end, group, cardinalities, pool):
+ self._end = end
+ self._group = group
+ self._cardinalities = cardinalities
+ self._pool = pool
+
+ def __getattr__(self, attr):
+ method_cardinality = self._cardinalities.get(attr)
+ if method_cardinality is cardinality.Cardinality.UNARY_UNARY:
+ return _UnaryUnaryMultiCallable(self._end, self._group, attr, self._pool)
+ elif method_cardinality is cardinality.Cardinality.UNARY_STREAM:
+ return _UnaryStreamMultiCallable(self._end, self._group, attr, self._pool)
+ elif method_cardinality is cardinality.Cardinality.STREAM_UNARY:
+ return _StreamUnaryMultiCallable(self._end, self._group, attr, self._pool)
+ elif method_cardinality is cardinality.Cardinality.STREAM_STREAM:
+ return _StreamStreamMultiCallable(
+ self._end, self._group, attr, self._pool)
+ else:
+ raise AttributeError('_DynamicStub object has no attribute "%s"!' % attr)
+
+
+def _adapt_method_implementations(method_implementations, pool):
+ adapted_implementations = {}
+ for name, method_implementation in method_implementations.iteritems():
+ if method_implementation.style is style.Service.INLINE:
+ if method_implementation.cardinality is cardinality.Cardinality.UNARY_UNARY:
+ adapted_implementations[name] = _service.adapt_inline_unary_unary(
+ method_implementation.unary_unary_inline, pool)
+ elif method_implementation.cardinality is cardinality.Cardinality.UNARY_STREAM:
+ adapted_implementations[name] = _service.adapt_inline_unary_stream(
+ method_implementation.unary_stream_inline, pool)
+ elif method_implementation.cardinality is cardinality.Cardinality.STREAM_UNARY:
+ adapted_implementations[name] = _service.adapt_inline_stream_unary(
+ method_implementation.stream_unary_inline, pool)
+ elif method_implementation.cardinality is cardinality.Cardinality.STREAM_STREAM:
+ adapted_implementations[name] = _service.adapt_inline_stream_stream(
+ method_implementation.stream_stream_inline, pool)
+ elif method_implementation.style is style.Service.EVENT:
+ if method_implementation.cardinality is cardinality.Cardinality.UNARY_UNARY:
+ adapted_implementations[name] = _service.adapt_event_unary_unary(
+ method_implementation.unary_unary_event, pool)
+ elif method_implementation.cardinality is cardinality.Cardinality.UNARY_STREAM:
+ adapted_implementations[name] = _service.adapt_event_unary_stream(
+ method_implementation.unary_stream_event, pool)
+ elif method_implementation.cardinality is cardinality.Cardinality.STREAM_UNARY:
+ adapted_implementations[name] = _service.adapt_event_stream_unary(
+ method_implementation.stream_unary_event, pool)
+ elif method_implementation.cardinality is cardinality.Cardinality.STREAM_STREAM:
+ adapted_implementations[name] = _service.adapt_event_stream_stream(
+ method_implementation.stream_stream_event, pool)
+ return adapted_implementations
+
+
+def servicer(method_implementations, multi_method_implementation, pool):
+ """Creates a base.Servicer.
+
+ It is guaranteed that any passed face.MultiMethodImplementation will
+ only be called to service an RPC if there is no
+ face.MethodImplementation for the RPC method in the passed
+ method_implementations dictionary.
+
+ Args:
+ method_implementations: A dictionary from RPC method name to
+ face.MethodImplementation object to be used to service the named
+ RPC method.
+ multi_method_implementation: An face.MultiMethodImplementation to be
+ used to service any RPCs not serviced by the
+ face.MethodImplementations given in the method_implementations
+ dictionary, or None.
+ pool: A thread pool.
+
+ Returns:
+ A base.Servicer that services RPCs via the given implementations.
+ """
+ adapted_implementations = _adapt_method_implementations(
+ method_implementations, pool)
+ adapted_multi_method_implementation = _service.adapt_multi_method(
+ multi_method_implementation, pool)
+ return _BaseServicer(
+ adapted_implementations, adapted_multi_method_implementation)
+
+
+def generic_stub(end, pool):
+ """Creates an face.GenericStub.
+
+ Args:
+ end: A base.End.
+ pool: A futures.ThreadPoolExecutor.
+
+ Returns:
+ A face.GenericStub that performs RPCs via the given base.End.
+ """
+ return _GenericStub(end, pool)
+
+
+def dynamic_stub(end, group, cardinalities, pool):
+ """Creates an face.DynamicStub.
+
+ Args:
+ end: A base.End.
+ group: The group identifier for all RPCs to be made with the created
+ face.DynamicStub.
+ cardinalities: A dict from method identifier to cardinality.Cardinality
+ value identifying the cardinality of every RPC method to be supported by
+ the created face.DynamicStub.
+ pool: A futures.ThreadPoolExecutor.
+
+ Returns:
+ A face.DynamicStub that performs RPCs via the given base.End.
+ """
+ return _DynamicStub(end, group, cardinalities, pool)
diff --git a/src/python/grpcio/grpc/framework/interfaces/base/base.py b/src/python/grpcio/grpc/framework/interfaces/base/base.py
index 76e0a5bdae..bc52efb4c5 100644
--- a/src/python/grpcio/grpc/framework/interfaces/base/base.py
+++ b/src/python/grpcio/grpc/framework/interfaces/base/base.py
@@ -47,7 +47,26 @@ from grpc.framework.foundation import abandonment # pylint: disable=unused-impo
class NoSuchMethodError(Exception):
- """Indicates that an unrecognized operation has been called."""
+ """Indicates that an unrecognized operation has been called.
+
+ Attributes:
+ code: A code value to communicate to the other side of the operation along
+ with indication of operation termination. May be None.
+ details: A details value to communicate to the other side of the operation
+ along with indication of operation termination. May be None.
+ """
+
+ def __init__(self, code, details):
+ """Constructor.
+
+ Args:
+ code: A code value to communicate to the other side of the operation
+ along with indication of operation termination. May be None.
+ details: A details value to communicate to the other side of the
+ operation along with indication of operation termination. May be None.
+ """
+ self.code = code
+ self.details = details
@enum.unique
diff --git a/src/python/grpcio_test/grpc_interop/client.py b/src/python/grpcio_test/grpc_interop/client.py
index 2dd2103cbe..36afe6c096 100644
--- a/src/python/grpcio_test/grpc_interop/client.py
+++ b/src/python/grpcio_test/grpc_interop/client.py
@@ -70,7 +70,13 @@ def _oauth_access_token(args):
def _stub(args):
if args.oauth_scope:
- metadata_transformer = lambda x: [('Authorization', 'Bearer %s' % _oauth_access_token(args))]
+ if args.test_case == 'oauth2_auth_token':
+ access_token = _oauth_access_token(args)
+ metadata_transformer = lambda x: [
+ ('Authorization', 'Bearer %s' % access_token)]
+ else:
+ metadata_transformer = lambda x: [
+ ('Authorization', 'Bearer %s' % _oauth_access_token(args))]
else:
metadata_transformer = lambda x: []
if args.use_tls:
diff --git a/src/python/grpcio_test/grpc_interop/methods.py b/src/python/grpcio_test/grpc_interop/methods.py
index 7a831f3cbd..642458e892 100644
--- a/src/python/grpcio_test/grpc_interop/methods.py
+++ b/src/python/grpcio_test/grpc_interop/methods.py
@@ -360,6 +360,19 @@ def _service_account_creds(stub, args):
(response.oauth_scope, args.oauth_scope))
+def _oauth2_auth_token(stub, args):
+ json_key_filename = os.environ[
+ oauth2client_client.GOOGLE_APPLICATION_CREDENTIALS]
+ wanted_email = json.load(open(json_key_filename, 'rb'))['client_email']
+ response = _large_unary_common_behavior(stub, True, True)
+ if wanted_email != response.username:
+ raise ValueError(
+ 'expected username %s, got %s' % (wanted_email, response.username))
+ if args.oauth_scope.find(response.oauth_scope) == -1:
+ raise ValueError(
+ 'expected to find oauth scope "%s" in received "%s"' %
+ (response.oauth_scope, args.oauth_scope))
+
@enum.unique
class TestCase(enum.Enum):
EMPTY_UNARY = 'empty_unary'
@@ -371,6 +384,7 @@ class TestCase(enum.Enum):
CANCEL_AFTER_FIRST_RESPONSE = 'cancel_after_first_response'
COMPUTE_ENGINE_CREDS = 'compute_engine_creds'
SERVICE_ACCOUNT_CREDS = 'service_account_creds'
+ OAUTH2_AUTH_TOKEN = 'oauth2_auth_token'
TIMEOUT_ON_SLEEPING_SERVER = 'timeout_on_sleeping_server'
def test_interoperability(self, stub, args):
@@ -394,5 +408,7 @@ class TestCase(enum.Enum):
_compute_engine_creds(stub, args)
elif self is TestCase.SERVICE_ACCOUNT_CREDS:
_service_account_creds(stub, args)
+ elif self is TestCase.OAUTH2_AUTH_TOKEN:
+ _oauth2_auth_token(stub, args)
else:
raise NotImplementedError('Test case "%s" not implemented!' % self.name)
diff --git a/src/python/grpcio_test/grpc_test/_adapter/_links_test.py b/src/python/grpcio_test/grpc_test/_adapter/_links_test.py
index c4686b327a..4077b8e350 100644
--- a/src/python/grpcio_test/grpc_test/_adapter/_links_test.py
+++ b/src/python/grpcio_test/grpc_test/_adapter/_links_test.py
@@ -46,8 +46,8 @@ _TIMEOUT = 32
# TODO(nathaniel): End-to-end metadata testing.
def _transform_metadata(unused_metadata):
return (
- ('one unused key', 'one unused value'),
- ('another unused key', 'another unused value'),
+ ('one_unused_key', 'one unused value'),
+ ('another_unused_key', 'another unused value'),
)
diff --git a/src/python/grpcio_test/grpc_test/_core_over_links_base_interface_test.py b/src/python/grpcio_test/grpc_test/_core_over_links_base_interface_test.py
index 72b1ae5642..5ed5ec0b9a 100644
--- a/src/python/grpcio_test/grpc_test/_core_over_links_base_interface_test.py
+++ b/src/python/grpcio_test/grpc_test/_core_over_links_base_interface_test.py
@@ -27,7 +27,7 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""Tests the RPC Framework Core's implementation of the Base interface."""
+"""Tests Base interface compliance of the core-over-gRPC-links stack."""
import collections
import logging
@@ -45,11 +45,7 @@ from grpc_test.framework.common import test_constants
from grpc_test.framework.interfaces.base import test_cases
from grpc_test.framework.interfaces.base import test_interfaces
-_INVOCATION_INITIAL_METADATA = ((b'0', b'abc'), (b'1', b'def'), (b'2', b'ghi'),)
-_SERVICE_INITIAL_METADATA = ((b'3', b'jkl'), (b'4', b'mno'), (b'5', b'pqr'),)
-_SERVICE_TERMINAL_METADATA = ((b'6', b'stu'), (b'7', b'vwx'), (b'8', b'yza'),)
_CODE = _intermediary_low.Code.OK
-_MESSAGE = b'test message'
class _SerializationBehaviors(
@@ -95,7 +91,7 @@ class _Implementation(test_interfaces.Implementation):
service_grpc_link = service.service_link(
serialization_behaviors.request_deserializers,
serialization_behaviors.response_serializers)
- port = service_grpc_link.add_port(0, None)
+ port = service_grpc_link.add_port('[::]:0', None)
channel = _intermediary_low.Channel('localhost:%d' % port, None)
invocation_grpc_link = invocation.invocation_link(
channel, b'localhost',
@@ -117,16 +113,18 @@ class _Implementation(test_interfaces.Implementation):
service_grpc_link.stop_gracefully()
def invocation_initial_metadata(self):
- return _INVOCATION_INITIAL_METADATA
+ return grpc_test_common.INVOCATION_INITIAL_METADATA
def service_initial_metadata(self):
- return _SERVICE_INITIAL_METADATA
+ return grpc_test_common.SERVICE_INITIAL_METADATA
def invocation_completion(self):
return utilities.completion(None, None, None)
def service_completion(self):
- return utilities.completion(_SERVICE_TERMINAL_METADATA, _CODE, _MESSAGE)
+ return utilities.completion(
+ grpc_test_common.SERVICE_TERMINAL_METADATA, _CODE,
+ grpc_test_common.DETAILS)
def metadata_transmitted(self, original_metadata, transmitted_metadata):
return original_metadata is None or grpc_test_common.metadata_transmitted(
@@ -146,14 +144,6 @@ class _Implementation(test_interfaces.Implementation):
return True
-def setUpModule():
- logging.warn('setUpModule!')
-
-
-def tearDownModule():
- logging.warn('tearDownModule!')
-
-
def load_tests(loader, tests, pattern):
return unittest.TestSuite(
tests=tuple(
diff --git a/src/python/grpcio_test/grpc_test/_crust_over_core_over_links_face_interface_test.py b/src/python/grpcio_test/grpc_test/_crust_over_core_over_links_face_interface_test.py
new file mode 100644
index 0000000000..ce7c6f9e7a
--- /dev/null
+++ b/src/python/grpcio_test/grpc_test/_crust_over_core_over_links_face_interface_test.py
@@ -0,0 +1,159 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Tests Face compliance of the crust-over-core-over-gRPC-links stack."""
+
+import collections
+import unittest
+
+from grpc._adapter import _intermediary_low
+from grpc._links import invocation
+from grpc._links import service
+from grpc.framework.core import implementations as core_implementations
+from grpc.framework.crust import implementations as crust_implementations
+from grpc.framework.foundation import logging_pool
+from grpc.framework.interfaces.links import utilities
+from grpc_test import test_common as grpc_test_common
+from grpc_test.framework.common import test_constants
+from grpc_test.framework.interfaces.face import test_cases
+from grpc_test.framework.interfaces.face import test_interfaces
+
+
+class _SerializationBehaviors(
+ collections.namedtuple(
+ '_SerializationBehaviors',
+ ('request_serializers', 'request_deserializers', 'response_serializers',
+ 'response_deserializers',))):
+ pass
+
+
+def _serialization_behaviors_from_test_methods(test_methods):
+ request_serializers = {}
+ request_deserializers = {}
+ response_serializers = {}
+ response_deserializers = {}
+ for (group, method), test_method in test_methods.iteritems():
+ request_serializers[group, method] = test_method.serialize_request
+ request_deserializers[group, method] = test_method.deserialize_request
+ response_serializers[group, method] = test_method.serialize_response
+ response_deserializers[group, method] = test_method.deserialize_response
+ return _SerializationBehaviors(
+ request_serializers, request_deserializers, response_serializers,
+ response_deserializers)
+
+
+class _Implementation(test_interfaces.Implementation):
+
+ def instantiate(
+ self, methods, method_implementations, multi_method_implementation):
+ pool = logging_pool.pool(test_constants.POOL_SIZE)
+ servicer = crust_implementations.servicer(
+ method_implementations, multi_method_implementation, pool)
+ serialization_behaviors = _serialization_behaviors_from_test_methods(
+ methods)
+ invocation_end_link = core_implementations.invocation_end_link()
+ service_end_link = core_implementations.service_end_link(
+ servicer, test_constants.DEFAULT_TIMEOUT,
+ test_constants.MAXIMUM_TIMEOUT)
+ service_grpc_link = service.service_link(
+ serialization_behaviors.request_deserializers,
+ serialization_behaviors.response_serializers)
+ port = service_grpc_link.add_port('[::]:0', None)
+ channel = _intermediary_low.Channel('localhost:%d' % port, None)
+ invocation_grpc_link = invocation.invocation_link(
+ channel, b'localhost',
+ serialization_behaviors.request_serializers,
+ serialization_behaviors.response_deserializers)
+
+ invocation_end_link.join_link(invocation_grpc_link)
+ invocation_grpc_link.join_link(invocation_end_link)
+ service_grpc_link.join_link(service_end_link)
+ service_end_link.join_link(service_grpc_link)
+ service_end_link.start()
+ invocation_end_link.start()
+ invocation_grpc_link.start()
+ service_grpc_link.start()
+
+ generic_stub = crust_implementations.generic_stub(invocation_end_link, pool)
+ # TODO(nathaniel): Add a "groups" attribute to _digest.TestServiceDigest.
+ group = next(iter(methods))[0]
+ # TODO(nathaniel): Add a "cardinalities_by_group" attribute to
+ # _digest.TestServiceDigest.
+ cardinalities = {
+ method: method_object.cardinality()
+ for (group, method), method_object in methods.iteritems()}
+ dynamic_stub = crust_implementations.dynamic_stub(
+ invocation_end_link, group, cardinalities, pool)
+
+ return generic_stub, {group: dynamic_stub}, (
+ invocation_end_link, invocation_grpc_link, service_grpc_link,
+ service_end_link, pool)
+
+ def destantiate(self, memo):
+ (invocation_end_link, invocation_grpc_link, service_grpc_link,
+ service_end_link, pool) = memo
+ invocation_end_link.stop(0).wait()
+ invocation_grpc_link.stop()
+ service_grpc_link.stop_gracefully()
+ service_end_link.stop(0).wait()
+ invocation_end_link.join_link(utilities.NULL_LINK)
+ invocation_grpc_link.join_link(utilities.NULL_LINK)
+ service_grpc_link.join_link(utilities.NULL_LINK)
+ service_end_link.join_link(utilities.NULL_LINK)
+ pool.shutdown(wait=True)
+
+ def invocation_metadata(self):
+ return grpc_test_common.INVOCATION_INITIAL_METADATA
+
+ def initial_metadata(self):
+ return grpc_test_common.SERVICE_INITIAL_METADATA
+
+ def terminal_metadata(self):
+ return grpc_test_common.SERVICE_TERMINAL_METADATA
+
+ def code(self):
+ return _intermediary_low.Code.OK
+
+ def details(self):
+ return grpc_test_common.DETAILS
+
+ def metadata_transmitted(self, original_metadata, transmitted_metadata):
+ return original_metadata is None or grpc_test_common.metadata_transmitted(
+ original_metadata, transmitted_metadata)
+
+
+def load_tests(loader, tests, pattern):
+ return unittest.TestSuite(
+ tests=tuple(
+ loader.loadTestsFromTestCase(test_case_class)
+ for test_case_class in test_cases.test_cases(_Implementation())))
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/src/python/grpcio_test/grpc_test/_cython/adapter_low_test.py b/src/python/grpcio_test/grpc_test/_cython/adapter_low_test.py
index 9bab930e56..f1bec238cf 100644
--- a/src/python/grpcio_test/grpc_test/_cython/adapter_low_test.py
+++ b/src/python/grpcio_test/grpc_test/_cython/adapter_low_test.py
@@ -76,7 +76,7 @@ class InsecureServerInsecureClient(unittest.TestCase):
CLIENT_METADATA_BIN_VALUE = b'\0'*1000
SERVER_INITIAL_METADATA_KEY = 'init_me_me_me'
SERVER_INITIAL_METADATA_VALUE = 'whodawha?'
- SERVER_TRAILING_METADATA_KEY = 'California_is_in_a_drought'
+ SERVER_TRAILING_METADATA_KEY = 'california_is_in_a_drought'
SERVER_TRAILING_METADATA_VALUE = 'zomg it is'
SERVER_STATUS_CODE = _types.StatusCode.OK
SERVER_STATUS_DETAILS = 'our work is never over'
diff --git a/src/python/grpcio_test/grpc_test/_links/_transmission_test.py b/src/python/grpcio_test/grpc_test/_links/_transmission_test.py
index 02ddd512c2..0fef9b0c5a 100644
--- a/src/python/grpcio_test/grpc_test/_links/_transmission_test.py
+++ b/src/python/grpcio_test/grpc_test/_links/_transmission_test.py
@@ -50,7 +50,7 @@ class TransmissionTest(test_cases.TransmissionTest, unittest.TestCase):
service_link = service.service_link(
{self.group_and_method(): self.deserialize_request},
{self.group_and_method(): self.serialize_response})
- port = service_link.add_port(0, None)
+ port = service_link.add_port('[::]:0', None)
service_link.start()
channel = _intermediary_low.Channel('localhost:%d' % port, None)
invocation_link = invocation.invocation_link(
@@ -66,9 +66,9 @@ class TransmissionTest(test_cases.TransmissionTest, unittest.TestCase):
def create_invocation_initial_metadata(self):
return (
- ('first invocation initial metadata key', 'just a string value'),
- ('second invocation initial metadata key', '0123456789'),
- ('third invocation initial metadata key-bin', '\x00\x57' * 100),
+ ('first_invocation_initial_metadata_key', 'just a string value'),
+ ('second_invocation_initial_metadata_key', '0123456789'),
+ ('third_invocation_initial_metadata_key-bin', '\x00\x57' * 100),
)
def create_invocation_terminal_metadata(self):
@@ -76,16 +76,16 @@ class TransmissionTest(test_cases.TransmissionTest, unittest.TestCase):
def create_service_initial_metadata(self):
return (
- ('first service initial metadata key', 'just another string value'),
- ('second service initial metadata key', '9876543210'),
- ('third service initial metadata key-bin', '\x00\x59\x02' * 100),
+ ('first_service_initial_metadata_key', 'just another string value'),
+ ('second_service_initial_metadata_key', '9876543210'),
+ ('third_service_initial_metadata_key-bin', '\x00\x59\x02' * 100),
)
def create_service_terminal_metadata(self):
return (
- ('first service terminal metadata key', 'yet another string value'),
- ('second service terminal metadata key', 'abcdefghij'),
- ('third service terminal metadata key-bin', '\x00\x37' * 100),
+ ('first_service_terminal_metadata_key', 'yet another string value'),
+ ('second_service_terminal_metadata_key', 'abcdefghij'),
+ ('third_service_terminal_metadata_key-bin', '\x00\x37' * 100),
)
def create_invocation_completion(self):
@@ -116,7 +116,7 @@ class RoundTripTest(unittest.TestCase):
identity_transformation, identity_transformation)
service_mate = test_utilities.RecordingLink()
service_link.join_link(service_mate)
- port = service_link.add_port(0, None)
+ port = service_link.add_port('[::]:0', None)
service_link.start()
channel = _intermediary_low.Channel('localhost:%d' % port, None)
invocation_link = invocation.invocation_link(
@@ -160,7 +160,7 @@ class RoundTripTest(unittest.TestCase):
{(test_group, test_method): scenario.serialize_response})
service_mate = test_utilities.RecordingLink()
service_link.join_link(service_mate)
- port = service_link.add_port(0, None)
+ port = service_link.add_port('[::]:0', None)
service_link.start()
channel = _intermediary_low.Channel('localhost:%d' % port, None)
invocation_link = invocation.invocation_link(
diff --git a/src/python/grpcio_test/grpc_test/beta/__init__.py b/src/python/grpcio_test/grpc_test/beta/__init__.py
new file mode 100644
index 0000000000..7086519106
--- /dev/null
+++ b/src/python/grpcio_test/grpc_test/beta/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
diff --git a/src/python/grpcio_test/grpc_test/beta/_connectivity_channel_test.py b/src/python/grpcio_test/grpc_test/beta/_connectivity_channel_test.py
new file mode 100644
index 0000000000..038464889d
--- /dev/null
+++ b/src/python/grpcio_test/grpc_test/beta/_connectivity_channel_test.py
@@ -0,0 +1,180 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Tests of grpc.beta._connectivity_channel."""
+
+import threading
+import time
+import unittest
+
+from grpc._adapter import _low
+from grpc._adapter import _types
+from grpc.beta import _connectivity_channel
+from grpc_test.framework.common import test_constants
+
+_MAPPING_FUNCTION = lambda integer: integer * 200 + 17
+_MAPPING = {
+ state: _MAPPING_FUNCTION(state) for state in _types.ConnectivityState}
+_IDLE, _CONNECTING, _READY, _TRANSIENT_FAILURE, _FATAL_FAILURE = map(
+ _MAPPING_FUNCTION, _types.ConnectivityState)
+
+
+def _drive_completion_queue(completion_queue):
+ while True:
+ event = completion_queue.next(time.time() + 24 * 60 * 60)
+ if event.type == _types.EventType.QUEUE_SHUTDOWN:
+ break
+
+
+class _Callback(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._connectivities = []
+
+ def update(self, connectivity):
+ with self._condition:
+ self._connectivities.append(connectivity)
+ self._condition.notify()
+
+ def connectivities(self):
+ with self._condition:
+ return tuple(self._connectivities)
+
+ def block_until_connectivities_satisfy(self, predicate):
+ with self._condition:
+ while True:
+ connectivities = tuple(self._connectivities)
+ if predicate(connectivities):
+ return connectivities
+ else:
+ self._condition.wait()
+
+
+class ChannelConnectivityTest(unittest.TestCase):
+
+ def test_lonely_channel_connectivity(self):
+ low_channel = _low.Channel('localhost:12345', ())
+ callback = _Callback()
+
+ connectivity_channel = _connectivity_channel.ConnectivityChannel(
+ low_channel, _MAPPING)
+ connectivity_channel.subscribe(callback.update, try_to_connect=False)
+ first_connectivities = callback.block_until_connectivities_satisfy(bool)
+ connectivity_channel.subscribe(callback.update, try_to_connect=True)
+ second_connectivities = callback.block_until_connectivities_satisfy(
+ lambda connectivities: 2 <= len(connectivities))
+ # Wait for a connection that will never happen.
+ time.sleep(test_constants.SHORT_TIMEOUT)
+ third_connectivities = callback.connectivities()
+ connectivity_channel.unsubscribe(callback.update)
+ fourth_connectivities = callback.connectivities()
+ connectivity_channel.unsubscribe(callback.update)
+ fifth_connectivities = callback.connectivities()
+
+ self.assertSequenceEqual((_IDLE,), first_connectivities)
+ self.assertNotIn(_READY, second_connectivities)
+ self.assertNotIn(_READY, third_connectivities)
+ self.assertNotIn(_READY, fourth_connectivities)
+ self.assertNotIn(_READY, fifth_connectivities)
+
+ def test_immediately_connectable_channel_connectivity(self):
+ server_completion_queue = _low.CompletionQueue()
+ server = _low.Server(server_completion_queue, [])
+ port = server.add_http2_port('[::]:0')
+ server.start()
+ server_completion_queue_thread = threading.Thread(
+ target=_drive_completion_queue, args=(server_completion_queue,))
+ server_completion_queue_thread.start()
+ low_channel = _low.Channel('localhost:%d' % port, ())
+ first_callback = _Callback()
+ second_callback = _Callback()
+
+ connectivity_channel = _connectivity_channel.ConnectivityChannel(
+ low_channel, _MAPPING)
+ connectivity_channel.subscribe(first_callback.update, try_to_connect=False)
+ first_connectivities = first_callback.block_until_connectivities_satisfy(
+ bool)
+ # Wait for a connection that will never happen because try_to_connect=True
+ # has not yet been passed.
+ time.sleep(test_constants.SHORT_TIMEOUT)
+ second_connectivities = first_callback.connectivities()
+ connectivity_channel.subscribe(second_callback.update, try_to_connect=True)
+ third_connectivities = first_callback.block_until_connectivities_satisfy(
+ lambda connectivities: 2 <= len(connectivities))
+ fourth_connectivities = second_callback.block_until_connectivities_satisfy(
+ bool)
+ # Wait for a connection that will happen (or may already have happened).
+ first_callback.block_until_connectivities_satisfy(
+ lambda connectivities: _READY in connectivities)
+ second_callback.block_until_connectivities_satisfy(
+ lambda connectivities: _READY in connectivities)
+ connectivity_channel.unsubscribe(first_callback.update)
+ connectivity_channel.unsubscribe(second_callback.update)
+
+ server.shutdown()
+ server_completion_queue.shutdown()
+ server_completion_queue_thread.join()
+
+ self.assertSequenceEqual((_IDLE,), first_connectivities)
+ self.assertSequenceEqual((_IDLE,), second_connectivities)
+ self.assertNotIn(_TRANSIENT_FAILURE, third_connectivities)
+ self.assertNotIn(_FATAL_FAILURE, third_connectivities)
+ self.assertNotIn(_TRANSIENT_FAILURE, fourth_connectivities)
+ self.assertNotIn(_FATAL_FAILURE, fourth_connectivities)
+
+ def test_reachable_then_unreachable_channel_connectivity(self):
+ server_completion_queue = _low.CompletionQueue()
+ server = _low.Server(server_completion_queue, [])
+ port = server.add_http2_port('[::]:0')
+ server.start()
+ server_completion_queue_thread = threading.Thread(
+ target=_drive_completion_queue, args=(server_completion_queue,))
+ server_completion_queue_thread.start()
+ low_channel = _low.Channel('localhost:%d' % port, ())
+ callback = _Callback()
+
+ connectivity_channel = _connectivity_channel.ConnectivityChannel(
+ low_channel, _MAPPING)
+ connectivity_channel.subscribe(callback.update, try_to_connect=True)
+ callback.block_until_connectivities_satisfy(
+ lambda connectivities: _READY in connectivities)
+ # Now take down the server and confirm that channel readiness is repudiated.
+ server.shutdown()
+ callback.block_until_connectivities_satisfy(
+ lambda connectivities: connectivities[-1] is not _READY)
+ connectivity_channel.unsubscribe(callback.update)
+
+ server.shutdown()
+ server_completion_queue.shutdown()
+ server_completion_queue_thread.join()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/src/python/grpcio_test/grpc_test/beta/_utilities_test.py b/src/python/grpcio_test/grpc_test/beta/_utilities_test.py
new file mode 100644
index 0000000000..998e74ccf4
--- /dev/null
+++ b/src/python/grpcio_test/grpc_test/beta/_utilities_test.py
@@ -0,0 +1,123 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Tests of grpc.beta.utilities."""
+
+import threading
+import time
+import unittest
+
+from grpc._adapter import _low
+from grpc._adapter import _types
+from grpc.beta import beta
+from grpc.beta import utilities
+from grpc.framework.foundation import future
+from grpc_test.framework.common import test_constants
+
+
+def _drive_completion_queue(completion_queue):
+ while True:
+ event = completion_queue.next(time.time() + 24 * 60 * 60)
+ if event.type == _types.EventType.QUEUE_SHUTDOWN:
+ break
+
+
+class _Callback(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._value = None
+
+ def accept_value(self, value):
+ with self._condition:
+ self._value = value
+ self._condition.notify_all()
+
+ def block_until_called(self):
+ with self._condition:
+ while self._value is None:
+ self._condition.wait()
+ return self._value
+
+
+class ChannelConnectivityTest(unittest.TestCase):
+
+ def test_lonely_channel_connectivity(self):
+ channel = beta.create_insecure_channel('localhost', 12345)
+ callback = _Callback()
+
+ ready_future = utilities.channel_ready_future(channel)
+ ready_future.add_done_callback(callback.accept_value)
+ with self.assertRaises(future.TimeoutError):
+ ready_future.result(test_constants.SHORT_TIMEOUT)
+ self.assertFalse(ready_future.cancelled())
+ self.assertFalse(ready_future.done())
+ self.assertTrue(ready_future.running())
+ ready_future.cancel()
+ value_passed_to_callback = callback.block_until_called()
+ self.assertIs(ready_future, value_passed_to_callback)
+ self.assertTrue(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+
+ def test_immediately_connectable_channel_connectivity(self):
+ server_completion_queue = _low.CompletionQueue()
+ server = _low.Server(server_completion_queue, [])
+ port = server.add_http2_port('[::]:0')
+ server.start()
+ server_completion_queue_thread = threading.Thread(
+ target=_drive_completion_queue, args=(server_completion_queue,))
+ server_completion_queue_thread.start()
+ channel = beta.create_insecure_channel('localhost', port)
+ callback = _Callback()
+
+ try:
+ ready_future = utilities.channel_ready_future(channel)
+ ready_future.add_done_callback(callback.accept_value)
+ self.assertIsNone(
+ ready_future.result(test_constants.SHORT_TIMEOUT))
+ value_passed_to_callback = callback.block_until_called()
+ self.assertIs(ready_future, value_passed_to_callback)
+ self.assertFalse(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+ # Cancellation after maturity has no effect.
+ ready_future.cancel()
+ self.assertFalse(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+ finally:
+ ready_future.cancel()
+ server.shutdown()
+ server_completion_queue.shutdown()
+ server_completion_queue_thread.join()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/src/python/grpcio_test/grpc_test/framework/_crust_over_core_face_interface_test.py b/src/python/grpcio_test/grpc_test/framework/_crust_over_core_face_interface_test.py
new file mode 100644
index 0000000000..30bb85f6c3
--- /dev/null
+++ b/src/python/grpcio_test/grpc_test/framework/_crust_over_core_face_interface_test.py
@@ -0,0 +1,111 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Tests Face interface compliance of the crust-over-core stack."""
+
+import collections
+import unittest
+
+from grpc.framework.core import implementations as core_implementations
+from grpc.framework.crust import implementations as crust_implementations
+from grpc.framework.foundation import logging_pool
+from grpc.framework.interfaces.links import utilities
+from grpc_test.framework.common import test_constants
+from grpc_test.framework.interfaces.face import test_cases
+from grpc_test.framework.interfaces.face import test_interfaces
+from grpc_test.framework.interfaces.links import test_utilities
+
+
+class _Implementation(test_interfaces.Implementation):
+
+ def instantiate(
+ self, methods, method_implementations, multi_method_implementation):
+ pool = logging_pool.pool(test_constants.POOL_SIZE)
+ servicer = crust_implementations.servicer(
+ method_implementations, multi_method_implementation, pool)
+
+ service_end_link = core_implementations.service_end_link(
+ servicer, test_constants.DEFAULT_TIMEOUT,
+ test_constants.MAXIMUM_TIMEOUT)
+ invocation_end_link = core_implementations.invocation_end_link()
+ invocation_end_link.join_link(service_end_link)
+ service_end_link.join_link(invocation_end_link)
+ service_end_link.start()
+ invocation_end_link.start()
+
+ generic_stub = crust_implementations.generic_stub(invocation_end_link, pool)
+ # TODO(nathaniel): Add a "groups" attribute to _digest.TestServiceDigest.
+ group = next(iter(methods))[0]
+ # TODO(nathaniel): Add a "cardinalities_by_group" attribute to
+ # _digest.TestServiceDigest.
+ cardinalities = {
+ method: method_object.cardinality()
+ for (group, method), method_object in methods.iteritems()}
+ dynamic_stub = crust_implementations.dynamic_stub(
+ invocation_end_link, group, cardinalities, pool)
+
+ return generic_stub, {group: dynamic_stub}, (
+ invocation_end_link, service_end_link, pool)
+
+ def destantiate(self, memo):
+ invocation_end_link, service_end_link, pool = memo
+ invocation_end_link.stop(0).wait()
+ service_end_link.stop(0).wait()
+ invocation_end_link.join_link(utilities.NULL_LINK)
+ service_end_link.join_link(utilities.NULL_LINK)
+ pool.shutdown(wait=True)
+
+ def invocation_metadata(self):
+ return object()
+
+ def initial_metadata(self):
+ return object()
+
+ def terminal_metadata(self):
+ return object()
+
+ def code(self):
+ return object()
+
+ def details(self):
+ return object()
+
+ def metadata_transmitted(self, original_metadata, transmitted_metadata):
+ return original_metadata is transmitted_metadata
+
+
+def load_tests(loader, tests, pattern):
+ return unittest.TestSuite(
+ tests=tuple(
+ loader.loadTestsFromTestCase(test_case_class)
+ for test_case_class in test_cases.test_cases(_Implementation())))
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/src/python/grpcio_test/grpc_test/framework/interfaces/base/test_cases.py b/src/python/grpcio_test/grpc_test/framework/interfaces/base/test_cases.py
index 5c8b176da4..87332cf612 100644
--- a/src/python/grpcio_test/grpc_test/framework/interfaces/base/test_cases.py
+++ b/src/python/grpcio_test/grpc_test/framework/interfaces/base/test_cases.py
@@ -134,7 +134,7 @@ class _Servicer(base.Servicer):
if group != self._group or method != self._method:
controller.fail(
'%s != %s or %s != %s' % (group, self._group, method, self._method))
- raise base.NoSuchMethodError()
+ raise base.NoSuchMethodError(None, None)
else:
operator = _Operator(
controller, controller.on_service_advance, self._pool,
diff --git a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_3069_test_constant.py b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_3069_test_constant.py
new file mode 100644
index 0000000000..363d9ce8f1
--- /dev/null
+++ b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_3069_test_constant.py
@@ -0,0 +1,37 @@
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""A test constant working around issue 3069."""
+
+# test_constants is referenced from specification in this module.
+from grpc_test.framework.common import test_constants # pylint: disable=unused-import
+
+# TODO(issue 3069): Replace uses of this constant with
+# test_constants.SHORT_TIMEOUT.
+REALLY_SHORT_TIMEOUT = 0.1
diff --git a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_blocking_invocation_inline_service.py b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_blocking_invocation_inline_service.py
index 857ad5cf3e..8804f3f223 100644
--- a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_blocking_invocation_inline_service.py
+++ b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_blocking_invocation_inline_service.py
@@ -37,6 +37,7 @@ from grpc.framework.interfaces.face import face
from grpc_test.framework.common import test_constants
from grpc_test.framework.common import test_control
from grpc_test.framework.common import test_coverage
+from grpc_test.framework.interfaces.face import _3069_test_constant
from grpc_test.framework.interfaces.face import _digest
from grpc_test.framework.interfaces.face import _stock_service
from grpc_test.framework.interfaces.face import test_interfaces # pylint: disable=unused-import
@@ -170,7 +171,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause(), self.assertRaises(
face.ExpirationError):
self._invoker.blocking(group, method)(
- request, test_constants.SHORT_TIMEOUT)
+ request, _3069_test_constant.REALLY_SHORT_TIMEOUT)
def testExpiredUnaryRequestStreamResponse(self):
for (group, method), test_messages_sequence in (
@@ -181,7 +182,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause(), self.assertRaises(
face.ExpirationError):
response_iterator = self._invoker.blocking(group, method)(
- request, test_constants.SHORT_TIMEOUT)
+ request, _3069_test_constant.REALLY_SHORT_TIMEOUT)
list(response_iterator)
def testExpiredStreamRequestUnaryResponse(self):
@@ -193,7 +194,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause(), self.assertRaises(
face.ExpirationError):
self._invoker.blocking(group, method)(
- iter(requests), test_constants.SHORT_TIMEOUT)
+ iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT)
def testExpiredStreamRequestStreamResponse(self):
for (group, method), test_messages_sequence in (
@@ -204,7 +205,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause(), self.assertRaises(
face.ExpirationError):
response_iterator = self._invoker.blocking(group, method)(
- iter(requests), test_constants.SHORT_TIMEOUT)
+ iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT)
list(response_iterator)
def testFailedUnaryRequestUnaryResponse(self):
diff --git a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_event_invocation_synchronous_event_service.py b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_event_invocation_synchronous_event_service.py
index ea5cdeaea3..5a78b4bed2 100644
--- a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_event_invocation_synchronous_event_service.py
+++ b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_event_invocation_synchronous_event_service.py
@@ -37,6 +37,7 @@ from grpc.framework.interfaces.face import face
from grpc_test.framework.common import test_constants
from grpc_test.framework.common import test_control
from grpc_test.framework.common import test_coverage
+from grpc_test.framework.interfaces.face import _3069_test_constant
from grpc_test.framework.interfaces.face import _digest
from grpc_test.framework.interfaces.face import _receiver
from grpc_test.framework.interfaces.face import _stock_service
@@ -264,7 +265,8 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause():
self._invoker.event(group, method)(
- request, receiver, receiver.abort, test_constants.SHORT_TIMEOUT)
+ request, receiver, receiver.abort,
+ _3069_test_constant.REALLY_SHORT_TIMEOUT)
receiver.block_until_terminated()
self.assertIs(face.Abortion.Kind.EXPIRED, receiver.abortion().kind)
@@ -278,7 +280,8 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause():
self._invoker.event(group, method)(
- request, receiver, receiver.abort, test_constants.SHORT_TIMEOUT)
+ request, receiver, receiver.abort,
+ _3069_test_constant.REALLY_SHORT_TIMEOUT)
receiver.block_until_terminated()
self.assertIs(face.Abortion.Kind.EXPIRED, receiver.abortion().kind)
@@ -290,7 +293,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
receiver = _receiver.Receiver()
self._invoker.event(group, method)(
- receiver, receiver.abort, test_constants.SHORT_TIMEOUT)
+ receiver, receiver.abort, _3069_test_constant.REALLY_SHORT_TIMEOUT)
receiver.block_until_terminated()
self.assertIs(face.Abortion.Kind.EXPIRED, receiver.abortion().kind)
@@ -303,7 +306,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
receiver = _receiver.Receiver()
call_consumer = self._invoker.event(group, method)(
- receiver, receiver.abort, test_constants.SHORT_TIMEOUT)
+ receiver, receiver.abort, _3069_test_constant.REALLY_SHORT_TIMEOUT)
for request in requests:
call_consumer.consume(request)
receiver.block_until_terminated()
diff --git a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py
index a649362cef..d1107e1576 100644
--- a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py
+++ b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py
@@ -40,6 +40,7 @@ from grpc.framework.interfaces.face import face
from grpc_test.framework.common import test_constants
from grpc_test.framework.common import test_control
from grpc_test.framework.common import test_coverage
+from grpc_test.framework.interfaces.face import _3069_test_constant
from grpc_test.framework.interfaces.face import _digest
from grpc_test.framework.interfaces.face import _stock_service
from grpc_test.framework.interfaces.face import test_interfaces # pylint: disable=unused-import
@@ -265,7 +266,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause():
response_future = self._invoker.future(
- group, method)(request, test_constants.SHORT_TIMEOUT)
+ group, method)(request, _3069_test_constant.REALLY_SHORT_TIMEOUT)
self.assertIsInstance(
response_future.exception(), face.ExpirationError)
with self.assertRaises(face.ExpirationError):
@@ -279,7 +280,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause():
response_iterator = self._invoker.future(group, method)(
- request, test_constants.SHORT_TIMEOUT)
+ request, _3069_test_constant.REALLY_SHORT_TIMEOUT)
with self.assertRaises(face.ExpirationError):
list(response_iterator)
@@ -291,7 +292,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause():
response_future = self._invoker.future(group, method)(
- iter(requests), test_constants.SHORT_TIMEOUT)
+ iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT)
self.assertIsInstance(
response_future.exception(), face.ExpirationError)
with self.assertRaises(face.ExpirationError):
@@ -305,7 +306,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.pause():
response_iterator = self._invoker.future(group, method)(
- iter(requests), test_constants.SHORT_TIMEOUT)
+ iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT)
with self.assertRaises(face.ExpirationError):
list(response_iterator)
@@ -317,7 +318,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.fail():
response_future = self._invoker.future(group, method)(
- request, test_constants.SHORT_TIMEOUT)
+ request, _3069_test_constant.REALLY_SHORT_TIMEOUT)
# Because the servicer fails outside of the thread from which the
# servicer-side runtime called into it its failure is
@@ -340,7 +341,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
# expiration of the RPC.
with self._control.fail(), self.assertRaises(face.ExpirationError):
response_iterator = self._invoker.future(group, method)(
- request, test_constants.SHORT_TIMEOUT)
+ request, _3069_test_constant.REALLY_SHORT_TIMEOUT)
list(response_iterator)
def testFailedStreamRequestUnaryResponse(self):
@@ -351,7 +352,7 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
with self._control.fail():
response_future = self._invoker.future(group, method)(
- iter(requests), test_constants.SHORT_TIMEOUT)
+ iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT)
# Because the servicer fails outside of the thread from which the
# servicer-side runtime called into it its failure is
@@ -374,5 +375,5 @@ class TestCase(test_coverage.Coverage, unittest.TestCase):
# expiration of the RPC.
with self._control.fail(), self.assertRaises(face.ExpirationError):
response_iterator = self._invoker.future(group, method)(
- iter(requests), test_constants.SHORT_TIMEOUT)
+ iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT)
list(response_iterator)
diff --git a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_stock_service.py b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_stock_service.py
index 1dd2ec3633..808e2c4e36 100644
--- a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_stock_service.py
+++ b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_stock_service.py
@@ -1,4 +1,4 @@
-B# Copyright 2015, Google Inc.
+# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
diff --git a/src/python/grpcio_test/grpc_test/test_common.py b/src/python/grpcio_test/grpc_test/test_common.py
index f8e1f1e43f..44284be88b 100644
--- a/src/python/grpcio_test/grpc_test/test_common.py
+++ b/src/python/grpcio_test/grpc_test/test_common.py
@@ -31,6 +31,11 @@
import collections
+INVOCATION_INITIAL_METADATA = ((b'0', b'abc'), (b'1', b'def'), (b'2', b'ghi'),)
+SERVICE_INITIAL_METADATA = ((b'3', b'jkl'), (b'4', b'mno'), (b'5', b'pqr'),)
+SERVICE_TERMINAL_METADATA = ((b'6', b'stu'), (b'7', b'vwx'), (b'8', b'yza'),)
+DETAILS = b'test details'
+
def metadata_transmitted(original_metadata, transmitted_metadata):
"""Judges whether or not metadata was acceptably transmitted.
diff --git a/src/ruby/ext/grpc/rb_channel.c b/src/ruby/ext/grpc/rb_channel.c
index 6491aa4fb4..90afdc3fe1 100644
--- a/src/ruby/ext/grpc/rb_channel.c
+++ b/src/ruby/ext/grpc/rb_channel.c
@@ -150,7 +150,7 @@ static VALUE grpc_rb_channel_init(int argc, VALUE *argv, VALUE self) {
ch = grpc_insecure_channel_create(target_chars, &args, NULL);
} else {
creds = grpc_rb_get_wrapped_credentials(credentials);
- ch = grpc_secure_channel_create(creds, target_chars, &args);
+ ch = grpc_secure_channel_create(creds, target_chars, &args, NULL);
}
if (args.args != NULL) {
xfree(args.args); /* Allocated by grpc_rb_hash_convert_to_channel_args */
diff --git a/src/ruby/ext/grpc/rb_credentials.c b/src/ruby/ext/grpc/rb_credentials.c
index a9dcdbce9f..ac3804df6f 100644
--- a/src/ruby/ext/grpc/rb_credentials.c
+++ b/src/ruby/ext/grpc/rb_credentials.c
@@ -154,7 +154,7 @@ static VALUE grpc_rb_default_credentials_create(VALUE cls) {
Creates the default credential instances. */
static VALUE grpc_rb_compute_engine_credentials_create(VALUE cls) {
grpc_rb_credentials *wrapper = ALLOC(grpc_rb_credentials);
- wrapper->wrapped = grpc_compute_engine_credentials_create();
+ wrapper->wrapped = grpc_compute_engine_credentials_create(NULL);
if (wrapper->wrapped == NULL) {
rb_raise(rb_eRuntimeError,
"could not create composite engine credentials, not sure why");
@@ -181,8 +181,8 @@ static VALUE grpc_rb_composite_credentials_create(VALUE self, VALUE other) {
TypedData_Get_Struct(other, grpc_rb_credentials,
&grpc_rb_credentials_data_type, other_wrapper);
wrapper = ALLOC(grpc_rb_credentials);
- wrapper->wrapped = grpc_composite_credentials_create(self_wrapper->wrapped,
- other_wrapper->wrapped);
+ wrapper->wrapped = grpc_composite_credentials_create(
+ self_wrapper->wrapped, other_wrapper->wrapped, NULL);
if (wrapper->wrapped == NULL) {
rb_raise(rb_eRuntimeError,
"could not create composite credentials, not sure why");
@@ -234,12 +234,13 @@ static VALUE grpc_rb_credentials_init(int argc, VALUE *argv, VALUE self) {
return Qnil;
}
if (pem_private_key == Qnil && pem_cert_chain == Qnil) {
- creds = grpc_ssl_credentials_create(RSTRING_PTR(pem_root_certs), NULL);
+ creds =
+ grpc_ssl_credentials_create(RSTRING_PTR(pem_root_certs), NULL, NULL);
} else {
key_cert_pair.private_key = RSTRING_PTR(pem_private_key);
key_cert_pair.cert_chain = RSTRING_PTR(pem_cert_chain);
creds = grpc_ssl_credentials_create(RSTRING_PTR(pem_root_certs),
- &key_cert_pair);
+ &key_cert_pair, NULL);
}
if (creds == NULL) {
rb_raise(rb_eRuntimeError, "could not create a credentials, not sure why");
diff --git a/src/ruby/ext/grpc/rb_server_credentials.c b/src/ruby/ext/grpc/rb_server_credentials.c
index 62c211d769..6af4c86c45 100644
--- a/src/ruby/ext/grpc/rb_server_credentials.c
+++ b/src/ruby/ext/grpc/rb_server_credentials.c
@@ -178,10 +178,11 @@ static VALUE grpc_rb_server_credentials_init(VALUE self, VALUE pem_root_certs,
key_cert_pair.cert_chain = RSTRING_PTR(pem_cert_chain);
/* TODO Add a force_client_auth parameter and pass it here. */
if (pem_root_certs == Qnil) {
- creds = grpc_ssl_server_credentials_create(NULL, &key_cert_pair, 1, 0);
+ creds =
+ grpc_ssl_server_credentials_create(NULL, &key_cert_pair, 1, 0, NULL);
} else {
creds = grpc_ssl_server_credentials_create(RSTRING_PTR(pem_root_certs),
- &key_cert_pair, 1, 0);
+ &key_cert_pair, 1, 0, NULL);
}
if (creds == NULL) {
rb_raise(rb_eRuntimeError, "could not create a credentials, not sure why");