diff options
Diffstat (limited to 'src')
138 files changed, 1361 insertions, 614 deletions
diff --git a/src/compiler/python_generator.cc b/src/compiler/python_generator.cc new file mode 100644 index 0000000000..cdd3d8a98a --- /dev/null +++ b/src/compiler/python_generator.cc @@ -0,0 +1,330 @@ +/* + * + * 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. + * + */ + +#include <cassert> +#include <cctype> +#include <map> +#include <ostream> +#include <sstream> + +#include "src/compiler/python_generator.h" +#include <google/protobuf/io/printer.h> +#include <google/protobuf/io/zero_copy_stream_impl_lite.h> +#include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/descriptor.h> + +using google::protobuf::FileDescriptor; +using google::protobuf::ServiceDescriptor; +using google::protobuf::MethodDescriptor; +using google::protobuf::io::Printer; +using google::protobuf::io::StringOutputStream; +using std::initializer_list; +using std::map; +using std::string; + +namespace grpc_python_generator { +namespace { +////////////////////////////////// +// BEGIN FORMATTING BOILERPLATE // +////////////////////////////////// + +// Converts an initializer list of the form { key0, value0, key1, value1, ... } +// into a map of key* to value*. Is merely a readability helper for later code. +map<string, string> ListToDict(const initializer_list<string>& values) { + assert(values.size() % 2 == 0); + map<string, string> value_map; + auto value_iter = values.begin(); + for (unsigned i = 0; i < values.size()/2; ++i) { + string key = *value_iter; + ++value_iter; + string value = *value_iter; + value_map[key] = value; + ++value_iter; + } + return value_map; +} + +// Provides RAII indentation handling. Use as: +// { +// IndentScope raii_my_indent_var_name_here(my_py_printer); +// // constructor indented my_py_printer +// ... +// // destructor called at end of scope, un-indenting my_py_printer +// } +class IndentScope { + public: + explicit IndentScope(Printer* printer) : printer_(printer) { + printer_->Indent(); + } + + ~IndentScope() { + printer_->Outdent(); + } + + private: + Printer* printer_; +}; + +//////////////////////////////// +// END FORMATTING BOILERPLATE // +//////////////////////////////// + +void PrintService(const ServiceDescriptor* service, + Printer* out) { + string doc = "<fill me in later!>"; + map<string, string> dict = ListToDict({ + "Service", service->name(), + "Documentation", doc, + }); + out->Print(dict, "class $Service$Service(object):\n"); + { + IndentScope raii_class_indent(out); + out->Print(dict, "\"\"\"$Documentation$\"\"\"\n"); + out->Print("def __init__(self):\n"); + { + IndentScope raii_method_indent(out); + out->Print("pass\n"); + } + } +} + +void PrintServicer(const ServiceDescriptor* service, + Printer* out) { + string doc = "<fill me in later!>"; + map<string, string> dict = ListToDict({ + "Service", service->name(), + "Documentation", doc, + }); + out->Print(dict, "class $Service$Servicer(object):\n"); + { + IndentScope raii_class_indent(out); + out->Print(dict, "\"\"\"$Documentation$\"\"\"\n"); + for (int i = 0; i < service->method_count(); ++i) { + auto meth = service->method(i); + out->Print("def $Method$(self, arg):\n", "Method", meth->name()); + { + IndentScope raii_method_indent(out); + out->Print("raise NotImplementedError()\n"); + } + } + } +} + +void PrintStub(const ServiceDescriptor* service, + Printer* out) { + string doc = "<fill me in later!>"; + map<string, string> dict = ListToDict({ + "Service", service->name(), + "Documentation", doc, + }); + out->Print(dict, "class $Service$Stub(object):\n"); + { + IndentScope raii_class_indent(out); + out->Print(dict, "\"\"\"$Documentation$\"\"\"\n"); + for (int i = 0; i < service->method_count(); ++i) { + const MethodDescriptor* meth = service->method(i); + auto methdict = ListToDict({"Method", meth->name()}); + out->Print(methdict, "def $Method$(self, arg):\n"); + { + IndentScope raii_method_indent(out); + out->Print("raise NotImplementedError()\n"); + } + out->Print(methdict, "$Method$.async = None\n"); + } + } +} + +void PrintStubImpl(const ServiceDescriptor* service, + Printer* out) { + map<string, string> dict = ListToDict({ + "Service", service->name(), + }); + out->Print(dict, "class _$Service$Stub($Service$Stub):\n"); + { + IndentScope raii_class_indent(out); + out->Print("def __init__(self, face_stub, default_timeout):\n"); + { + IndentScope raii_method_indent(out); + out->Print("self._face_stub = face_stub\n" + "self._default_timeout = default_timeout\n" + "stub_self = self\n"); + + for (int i = 0; i < service->method_count(); ++i) { + const MethodDescriptor* meth = service->method(i); + bool server_streaming = meth->server_streaming(); + bool client_streaming = meth->client_streaming(); + std::string blocking_call, future_call; + if (server_streaming) { + if (client_streaming) { + blocking_call = "stub_self._face_stub.inline_stream_in_stream_out"; + future_call = blocking_call; + } else { + blocking_call = "stub_self._face_stub.inline_value_in_stream_out"; + future_call = blocking_call; + } + } else { + if (client_streaming) { + blocking_call = "stub_self._face_stub.blocking_stream_in_value_out"; + future_call = "stub_self._face_stub.future_stream_in_value_out"; + } else { + blocking_call = "stub_self._face_stub.blocking_value_in_value_out"; + future_call = "stub_self._face_stub.future_value_in_value_out"; + } + } + // TODO(atash): use the solution described at + // http://stackoverflow.com/a/2982 to bind 'async' attribute + // functions to def'd functions instead of using callable attributes. + auto methdict = ListToDict({ + "Method", meth->name(), + "BlockingCall", blocking_call, + "FutureCall", future_call + }); + out->Print(methdict, "class $Method$(object):\n"); + { + IndentScope raii_callable_indent(out); + out->Print("def __call__(self, arg):\n"); + { + IndentScope raii_callable_call_indent(out); + out->Print(methdict, + "return $BlockingCall$(\"$Method$\", arg, " + "stub_self._default_timeout)\n"); + } + out->Print("def async(self, arg):\n"); + { + IndentScope raii_callable_async_indent(out); + out->Print(methdict, + "return $FutureCall$(\"$Method$\", arg, " + "stub_self._default_timeout)\n"); + } + } + out->Print(methdict, "self.$Method$ = $Method$()\n"); + } + } + } +} + +void PrintStubGenerators(const ServiceDescriptor* service, Printer* out) { + map<string, string> dict = ListToDict({ + "Service", service->name(), + }); + // Write out a generator of linked pairs of Server/Stub + out->Print(dict, "def mock_$Service$(servicer, default_timeout):\n"); + { + IndentScope raii_mock_indent(out); + out->Print("value_in_value_out = {}\n" + "value_in_stream_out = {}\n" + "stream_in_value_out = {}\n" + "stream_in_stream_out = {}\n"); + for (int i = 0; i < service->method_count(); ++i) { + const MethodDescriptor* meth = service->method(i); + std::string super_interface, meth_dict; + bool server_streaming = meth->server_streaming(); + bool client_streaming = meth->client_streaming(); + if (server_streaming) { + if (client_streaming) { + super_interface = "InlineStreamInStreamOutMethod"; + meth_dict = "stream_in_stream_out"; + } else { + super_interface = "InlineValueInStreamOutMethod"; + meth_dict = "value_in_stream_out"; + } + } else { + if (client_streaming) { + super_interface = "InlineStreamInValueOutMethod"; + meth_dict = "stream_in_value_out"; + } else { + super_interface = "InlineValueInValueOutMethod"; + meth_dict = "value_in_value_out"; + } + } + map<string, string> methdict = ListToDict({ + "Method", meth->name(), + "SuperInterface", super_interface, + "MethodDict", meth_dict + }); + out->Print( + methdict, "class $Method$(_face_interfaces.$SuperInterface$):\n"); + { + IndentScope raii_inline_class_indent(out); + out->Print("def service(self, request, context):\n"); + { + IndentScope raii_inline_class_fn_indent(out); + out->Print(methdict, "return servicer.$Method$(request)\n"); + } + } + out->Print(methdict, "$MethodDict$['$Method$'] = $Method$()\n"); + } + out->Print( + "face_linked_pair = _face_testing.server_and_stub(default_timeout," + "inline_value_in_value_out_methods=value_in_value_out," + "inline_value_in_stream_out_methods=value_in_stream_out," + "inline_stream_in_value_out_methods=stream_in_value_out," + "inline_stream_in_stream_out_methods=stream_in_stream_out)\n"); + out->Print("class LinkedPair(object):\n"); + { + IndentScope raii_linked_pair(out); + out->Print("def __init__(self, server, stub):\n"); + { + IndentScope raii_linked_pair_init(out); + out->Print("self.server = server\n" + "self.stub = stub\n"); + } + } + out->Print( + dict, + "stub = _$Service$Stub(face_linked_pair.stub, default_timeout)\n"); + out->Print("return LinkedPair(None, stub)\n"); + } +} + +} // namespace + +string GetServices(const FileDescriptor* file) { + string output; + StringOutputStream output_stream(&output); + Printer out(&output_stream, '$'); + out.Print("from grpc.framework.face import demonstration as _face_testing\n"); + out.Print("from grpc.framework.face import interfaces as _face_interfaces\n"); + + for (int i = 0; i < file->service_count(); ++i) { + auto service = file->service(i); + PrintService(service, &out); + PrintServicer(service, &out); + PrintStub(service, &out); + PrintStubImpl(service, &out); + PrintStubGenerators(service, &out); + } + return output; +} + +} // namespace grpc_python_generator diff --git a/src/compiler/python_generator.h b/src/compiler/python_generator.h new file mode 100644 index 0000000000..673ef7b23b --- /dev/null +++ b/src/compiler/python_generator.h @@ -0,0 +1,51 @@ +/* + * + * 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. + * + */ + +#ifndef __GRPC_COMPILER_PYTHON_GENERATOR_H__ +#define __GRPC_COMPILER_PYTHON_GENERATOR_H__ + +#include <string> + +namespace google { +namespace protobuf { +class FileDescriptor; +} // namespace protobuf +} // namespace google + +namespace grpc_python_generator { + +std::string GetServices(const google::protobuf::FileDescriptor* file); + +} // namespace grpc_python_generator + +#endif // __GRPC_COMPILER_PYTHON_GENERATOR_H__ diff --git a/src/compiler/python_plugin.cc b/src/compiler/python_plugin.cc new file mode 100644 index 0000000000..ebe3660619 --- /dev/null +++ b/src/compiler/python_plugin.cc @@ -0,0 +1,87 @@ +/* + * + * 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. + * + */ + +// Generates a Python gRPC service interface out of Protobuf IDL. + +#include <memory> +#include <string> + +#include "src/compiler/python_generator.h" +#include <google/protobuf/compiler/code_generator.h> +#include <google/protobuf/compiler/plugin.h> +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/zero_copy_stream.h> +#include <google/protobuf/descriptor.h> + +using google::protobuf::FileDescriptor; +using google::protobuf::compiler::CodeGenerator; +using google::protobuf::compiler::GeneratorContext; +using google::protobuf::compiler::PluginMain; +using google::protobuf::io::CodedOutputStream; +using google::protobuf::io::ZeroCopyOutputStream; +using std::string; + +class PythonGrpcGenerator : public CodeGenerator { + public: + PythonGrpcGenerator() {} + ~PythonGrpcGenerator() override {} + + bool Generate(const FileDescriptor* file, + const string& parameter, + GeneratorContext* context, + string* error) const override { + // Get output file name. + string file_name; + static const int proto_suffix_length = 6; // length of ".proto" + if (file->name().size() > proto_suffix_length && + file->name().find_last_of(".proto") == file->name().size() - 1) { + file_name = file->name().substr( + 0, file->name().size() - proto_suffix_length) + "_pb2.py"; + } else { + *error = "Invalid proto file name. Proto file must end with .proto"; + return false; + } + + std::unique_ptr<ZeroCopyOutputStream> output( + context->OpenForInsert(file_name, "module_scope")); + CodedOutputStream coded_out(output.get()); + string code = grpc_python_generator::GetServices(file); + coded_out.WriteRaw(code.data(), code.size()); + return true; + } +}; + +int main(int argc, char* argv[]) { + PythonGrpcGenerator generator; + return PluginMain(argc, argv, &generator); +} diff --git a/src/core/README.md b/src/core/README.md new file mode 100644 index 0000000000..407dc4f701 --- /dev/null +++ b/src/core/README.md @@ -0,0 +1,9 @@ +#Overview + +This directory contains source code for shared C library. Libraries in other languages in this repository (C++, Ruby, +Python, PHP, NodeJS, Objective-C) are layered on top of this library. + +#Status + +Alpha : Ready for early adopters + diff --git a/src/core/security/credentials.c b/src/core/security/credentials.c index 60e82d9dfa..a21c27bff9 100644 --- a/src/core/security/credentials.c +++ b/src/core/security/credentials.c @@ -336,6 +336,12 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response( grpc_credentials_status status = GRPC_CREDENTIALS_OK; grpc_json *json = NULL; + if (response == NULL) { + gpr_log(GPR_ERROR, "Received NULL response."); + status = GRPC_CREDENTIALS_ERROR; + goto end; + } + if (response->body_length > 0) { null_terminated_body = gpr_malloc(response->body_length + 1); null_terminated_body[response->body_length] = '\0'; diff --git a/src/core/security/json_token.c b/src/core/security/json_token.c index c85b0cd847..20d62e2b43 100644 --- a/src/core/security/json_token.c +++ b/src/core/security/json_token.c @@ -206,15 +206,14 @@ static char *encoded_jwt_claim(const grpc_auth_json_key *json_key, char *result = NULL; gpr_timespec now = gpr_now(); gpr_timespec expiration = gpr_time_add(now, token_lifetime); - /* log10(2^64) ~= 20 */ - char now_str[24]; - char expiration_str[24]; + char now_str[GPR_LTOA_MIN_BUFSIZE]; + char expiration_str[GPR_LTOA_MIN_BUFSIZE]; if (gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime) > 0) { gpr_log(GPR_INFO, "Cropping token lifetime to maximum allowed value."); expiration = gpr_time_add(now, grpc_max_auth_token_lifetime); } - sprintf(now_str, "%ld", now.tv_sec); - sprintf(expiration_str, "%ld", expiration.tv_sec); + gpr_ltoa(now.tv_sec, now_str); + gpr_ltoa(expiration.tv_sec, expiration_str); child = create_child(NULL, json, "iss", json_key->client_email, GRPC_JSON_STRING); diff --git a/src/core/support/cpu_posix.c b/src/core/support/cpu_posix.c index 91f722530c..91ce80c364 100644 --- a/src/core/support/cpu_posix.c +++ b/src/core/support/cpu_posix.c @@ -35,8 +35,6 @@ #ifdef GPR_CPU_POSIX -#include "src/core/support/cpu.h" - #include <errno.h> #include <unistd.h> #include <string.h> diff --git a/src/core/surface/call.c b/src/core/surface/call.c index 40caa93868..7cf3c0e4fd 100644 --- a/src/core/surface/call.c +++ b/src/core/surface/call.c @@ -360,8 +360,7 @@ static void unlock(grpc_call *call) { int num_completed_requests = call->num_completed_requests; int need_more_data = call->need_more_data && - !call->sending && - call->write_state >= WRITE_STATE_STARTED; + (call->write_state >= WRITE_STATE_STARTED || !call->is_client); int i; if (need_more_data) { @@ -536,14 +535,16 @@ static void finish_finish_step(void *pc, grpc_op_error error) { } static void finish_start_step(void *pc, grpc_op_error error) { - finish_send_op(pc, GRPC_IOREQ_SEND_INITIAL_METADATA, WRITE_STATE_STARTED, error); + finish_send_op(pc, GRPC_IOREQ_SEND_INITIAL_METADATA, WRITE_STATE_STARTED, + error); } static send_action choose_send_action(grpc_call *call) { switch (call->write_state) { case WRITE_STATE_INITIAL: if (is_op_live(call, GRPC_IOREQ_SEND_INITIAL_METADATA)) { - if (is_op_live(call, GRPC_IOREQ_SEND_MESSAGE) || is_op_live(call, GRPC_IOREQ_SEND_CLOSE)) { + if (is_op_live(call, GRPC_IOREQ_SEND_MESSAGE) || + is_op_live(call, GRPC_IOREQ_SEND_CLOSE)) { return SEND_BUFFERED_INITIAL_METADATA; } else { return SEND_INITIAL_METADATA; diff --git a/src/core/transport/chttp2/frame_data.c b/src/core/transport/chttp2/frame_data.c index 95c27ad286..a1ae9ed2e6 100644 --- a/src/core/transport/chttp2/frame_data.c +++ b/src/core/transport/chttp2/frame_data.c @@ -135,7 +135,7 @@ grpc_chttp2_parse_error grpc_chttp2_data_parser_parse( case GRPC_CHTTP2_DATA_FRAME: if (cur == end) { return GRPC_CHTTP2_PARSE_OK; - } else if (end - cur == p->frame_size) { + } else if ((gpr_uint32)(end - cur) == p->frame_size) { state->need_flush_reads = 1; grpc_sopb_add_slice(&p->incoming_sopb, gpr_slice_sub(slice, cur - beg, end - beg)); diff --git a/src/core/transport/chttp2_transport.c b/src/core/transport/chttp2_transport.c index 5b2d0a5e5b..982417ec8a 100644 --- a/src/core/transport/chttp2_transport.c +++ b/src/core/transport/chttp2_transport.c @@ -1631,7 +1631,7 @@ static int process_read(transport *t, gpr_slice slice) { /* fallthrough */ case DTS_FRAME: GPR_ASSERT(cur < end); - if (end - cur == t->incoming_frame_size) { + if ((gpr_uint32)(end - cur) == t->incoming_frame_size) { if (!parse_frame_slice( t, gpr_slice_sub_no_ref(slice, cur - beg, end - beg), 1)) { return 0; diff --git a/src/core/tsi/ssl_transport_security.c b/src/core/tsi/ssl_transport_security.c index 2e59275ff8..92fcb96dd2 100644 --- a/src/core/tsi/ssl_transport_security.c +++ b/src/core/tsi/ssl_transport_security.c @@ -1084,7 +1084,7 @@ static int server_handshaker_factory_alpn_callback( tsi_ssl_server_handshaker_factory* factory = (tsi_ssl_server_handshaker_factory*)arg; const unsigned char* client_current = in; - while ((client_current - in) < inlen) { + while ((unsigned int)(client_current - in) < inlen) { unsigned char client_current_len = *(client_current++); const unsigned char* server_current = factory->alpn_protocol_list; while ((server_current >= factory->alpn_protocol_list) && diff --git a/src/cpp/README.md b/src/cpp/README.md new file mode 100644 index 0000000000..a2eb9a08c8 --- /dev/null +++ b/src/cpp/README.md @@ -0,0 +1,9 @@ + +#Overview + +This directory contains source code for C++ implementation of gRPC. + +#Status + +Alpha : Ready for early adopters + diff --git a/src/cpp/server/server.cc b/src/cpp/server/server.cc index 7cccc58afd..f565d3aa5d 100644 --- a/src/cpp/server/server.cc +++ b/src/cpp/server/server.cc @@ -49,84 +49,6 @@ namespace grpc { -Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, - ServerCredentials* creds) - : started_(false), - shutdown_(false), - num_running_cb_(0), - thread_pool_(thread_pool), - thread_pool_owned_(thread_pool_owned), - secure_(creds != nullptr) { - if (creds) { - server_ = - grpc_secure_server_create(creds->GetRawCreds(), cq_.cq(), nullptr); - } else { - server_ = grpc_server_create(cq_.cq(), nullptr); - } -} - -Server::Server() { - // Should not be called. - GPR_ASSERT(false); -} - -Server::~Server() { - std::unique_lock<std::mutex> lock(mu_); - if (started_ && !shutdown_) { - lock.unlock(); - Shutdown(); - } else { - lock.unlock(); - } - grpc_server_destroy(server_); - if (thread_pool_owned_) { - delete thread_pool_; - } -} - -bool Server::RegisterService(RpcService* service) { - for (int i = 0; i < service->GetMethodCount(); ++i) { - RpcServiceMethod* method = service->GetMethod(i); - void* tag = - grpc_server_register_method(server_, method->name(), nullptr, cq_.cq()); - if (!tag) { - gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", - method->name()); - return false; - } - sync_methods_.emplace_back(method, tag); - } - return true; -} - -bool Server::RegisterAsyncService(AsynchronousService* service) { - GPR_ASSERT(service->dispatch_impl_ == nullptr && - "Can only register an asynchronous service against one server."); - service->dispatch_impl_ = this; - service->request_args_ = new void* [service->method_count_]; - for (size_t i = 0; i < service->method_count_; ++i) { - void* tag = - grpc_server_register_method(server_, service->method_names_[i], nullptr, - service->completion_queue()->cq()); - if (!tag) { - gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", - service->method_names_[i]); - return false; - } - service->request_args_[i] = tag; - } - return true; -} - -int Server::AddPort(const grpc::string& addr) { - GPR_ASSERT(!started_); - if (secure_) { - return grpc_server_add_secure_http2_port(server_, addr.c_str()); - } else { - return grpc_server_add_http2_port(server_, addr.c_str()); - } -} - class Server::SyncRequest final : public CompletionQueueTag { public: SyncRequest(RpcServiceMethod* method, void* tag) @@ -247,6 +169,84 @@ class Server::SyncRequest final : public CompletionQueueTag { grpc_completion_queue* cq_; }; +Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, + ServerCredentials* creds) + : started_(false), + shutdown_(false), + num_running_cb_(0), + thread_pool_(thread_pool), + thread_pool_owned_(thread_pool_owned), + secure_(creds != nullptr) { + if (creds) { + server_ = + grpc_secure_server_create(creds->GetRawCreds(), cq_.cq(), nullptr); + } else { + server_ = grpc_server_create(cq_.cq(), nullptr); + } +} + +Server::Server() { + // Should not be called. + GPR_ASSERT(false); +} + +Server::~Server() { + std::unique_lock<std::mutex> lock(mu_); + if (started_ && !shutdown_) { + lock.unlock(); + Shutdown(); + } else { + lock.unlock(); + } + grpc_server_destroy(server_); + if (thread_pool_owned_) { + delete thread_pool_; + } +} + +bool Server::RegisterService(RpcService* service) { + for (int i = 0; i < service->GetMethodCount(); ++i) { + RpcServiceMethod* method = service->GetMethod(i); + void* tag = + grpc_server_register_method(server_, method->name(), nullptr, cq_.cq()); + if (!tag) { + gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", + method->name()); + return false; + } + sync_methods_.emplace_back(method, tag); + } + return true; +} + +bool Server::RegisterAsyncService(AsynchronousService* service) { + GPR_ASSERT(service->dispatch_impl_ == nullptr && + "Can only register an asynchronous service against one server."); + service->dispatch_impl_ = this; + service->request_args_ = new void* [service->method_count_]; + for (size_t i = 0; i < service->method_count_; ++i) { + void* tag = + grpc_server_register_method(server_, service->method_names_[i], nullptr, + service->completion_queue()->cq()); + if (!tag) { + gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", + service->method_names_[i]); + return false; + } + service->request_args_[i] = tag; + } + return true; +} + +int Server::AddPort(const grpc::string& addr) { + GPR_ASSERT(!started_); + if (secure_) { + return grpc_server_add_secure_http2_port(server_, addr.c_str()); + } else { + return grpc_server_add_http2_port(server_, addr.c_str()); + } +} + bool Server::Start() { GPR_ASSERT(!started_); started_ = true; diff --git a/src/csharp/GrpcApi/MathExamples.cs b/src/csharp/GrpcApi/MathExamples.cs index 2202c52a27..97c91b1b1b 100644 --- a/src/csharp/GrpcApi/MathExamples.cs +++ b/src/csharp/GrpcApi/MathExamples.cs @@ -32,10 +32,10 @@ #endregion using System; -using System.Threading.Tasks; using System.Collections.Generic; using System.Reactive.Linq; -using Google.GRPC.Core.Utils; +using System.Threading.Tasks; +using Grpc.Core.Utils; namespace math { diff --git a/src/csharp/GrpcApi/MathGrpc.cs b/src/csharp/GrpcApi/MathGrpc.cs index 44e704e496..f938a24543 100644 --- a/src/csharp/GrpcApi/MathGrpc.cs +++ b/src/csharp/GrpcApi/MathGrpc.cs @@ -32,11 +32,11 @@ #endregion using System; -using System.Threading; -using System.Threading.Tasks; using System.Collections.Generic; using System.Reactive.Linq; -using Google.GRPC.Core; +using System.Threading; +using System.Threading.Tasks; +using Grpc.Core; namespace math { @@ -99,31 +99,31 @@ namespace math public DivReply Div(DivArgs request, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<DivArgs, DivReply>(divMethod, channel); + var call = new Grpc.Core.Call<DivArgs, DivReply>(divMethod, channel); return Calls.BlockingUnaryCall(call, request, token); } public Task<DivReply> DivAsync(DivArgs request, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<DivArgs, DivReply>(divMethod, channel); + var call = new Grpc.Core.Call<DivArgs, DivReply>(divMethod, channel); return Calls.AsyncUnaryCall(call, request, token); } public void Fib(FibArgs request, IObserver<Num> responseObserver, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<FibArgs, Num>(fibMethod, channel); + var call = new Grpc.Core.Call<FibArgs, Num>(fibMethod, channel); Calls.AsyncServerStreamingCall(call, request, responseObserver, token); } public ClientStreamingAsyncResult<Num, Num> Sum(CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<Num, Num>(sumMethod, channel); + var call = new Grpc.Core.Call<Num, Num>(sumMethod, channel); return Calls.AsyncClientStreamingCall(call, token); } public IObserver<DivArgs> DivMany(IObserver<DivReply> responseObserver, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<DivArgs, DivReply>(divManyMethod, channel); + var call = new Grpc.Core.Call<DivArgs, DivReply>(divManyMethod, channel); return Calls.DuplexStreamingCall(call, responseObserver, token); } } diff --git a/src/csharp/GrpcApi/MathServiceImpl.cs b/src/csharp/GrpcApi/MathServiceImpl.cs index 1a2f98f8b2..462fab4454 100644 --- a/src/csharp/GrpcApi/MathServiceImpl.cs +++ b/src/csharp/GrpcApi/MathServiceImpl.cs @@ -32,11 +32,11 @@ #endregion using System; -using System.Threading; -using System.Threading.Tasks; using System.Collections.Generic; using System.Reactive.Linq; -using Google.GRPC.Core.Utils; +using System.Threading; +using System.Threading.Tasks; +using Grpc.Core.Utils; namespace math { diff --git a/src/csharp/GrpcApi/Properties/AssemblyInfo.cs b/src/csharp/GrpcApi/Properties/AssemblyInfo.cs index e0a8e4357f..96f142dae9 100644 --- a/src/csharp/GrpcApi/Properties/AssemblyInfo.cs +++ b/src/csharp/GrpcApi/Properties/AssemblyInfo.cs @@ -8,13 +8,13 @@ using System.Runtime.CompilerServices; [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] -[assembly: AssemblyCopyright ("jtattermusch")] +[assembly: AssemblyCopyright ("Google Inc. All rights reserved.")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion ("1.0.*")] +[assembly: AssemblyVersion ("0.9.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] diff --git a/src/csharp/GrpcApi/TestServiceGrpc.cs b/src/csharp/GrpcApi/TestServiceGrpc.cs index 64d5c09563..15700e40ac 100644 --- a/src/csharp/GrpcApi/TestServiceGrpc.cs +++ b/src/csharp/GrpcApi/TestServiceGrpc.cs @@ -30,12 +30,13 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion + using System; -using System.Threading; -using System.Threading.Tasks; using System.Collections.Generic; using System.Reactive.Linq; -using Google.GRPC.Core; +using System.Threading; +using System.Threading.Tasks; +using Grpc.Core; namespace grpc.testing { @@ -119,49 +120,49 @@ namespace grpc.testing public Empty EmptyCall(Empty request, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<Empty, Empty>(emptyCallMethod, channel); + var call = new Grpc.Core.Call<Empty, Empty>(emptyCallMethod, channel); return Calls.BlockingUnaryCall(call, request, token); } public Task<Empty> EmptyCallAsync(Empty request, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<Empty, Empty>(emptyCallMethod, channel); + var call = new Grpc.Core.Call<Empty, Empty>(emptyCallMethod, channel); return Calls.AsyncUnaryCall(call, request, token); } public SimpleResponse UnaryCall(SimpleRequest request, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); + var call = new Grpc.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); return Calls.BlockingUnaryCall(call, request, token); } public Task<SimpleResponse> UnaryCallAsync(SimpleRequest request, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); + var call = new Grpc.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); return Calls.AsyncUnaryCall(call, request, token); } public void StreamingOutputCall(StreamingOutputCallRequest request, IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(streamingOutputCallMethod, channel); + var call = new Grpc.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(streamingOutputCallMethod, channel); Calls.AsyncServerStreamingCall(call, request, responseObserver, token); } public ClientStreamingAsyncResult<StreamingInputCallRequest, StreamingInputCallResponse> StreamingInputCall(CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<StreamingInputCallRequest, StreamingInputCallResponse>(streamingInputCallMethod, channel); + var call = new Grpc.Core.Call<StreamingInputCallRequest, StreamingInputCallResponse>(streamingInputCallMethod, channel); return Calls.AsyncClientStreamingCall(call, token); } public IObserver<StreamingOutputCallRequest> FullDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(fullDuplexCallMethod, channel); + var call = new Grpc.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(fullDuplexCallMethod, channel); return Calls.DuplexStreamingCall(call, responseObserver, token); } public IObserver<StreamingOutputCallRequest> HalfDuplexCall(IObserver<StreamingOutputCallResponse> responseObserver, CancellationToken token = default(CancellationToken)) { - var call = new Google.GRPC.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(halfDuplexCallMethod, channel); + var call = new Grpc.Core.Call<StreamingOutputCallRequest, StreamingOutputCallResponse>(halfDuplexCallMethod, channel); return Calls.DuplexStreamingCall(call, responseObserver, token); } } diff --git a/src/csharp/GrpcApiTests/MathClientServerTests.cs b/src/csharp/GrpcApiTests/MathClientServerTests.cs index 9056142097..767340d6f2 100644 --- a/src/csharp/GrpcApiTests/MathClientServerTests.cs +++ b/src/csharp/GrpcApiTests/MathClientServerTests.cs @@ -32,12 +32,12 @@ #endregion using System; -using NUnit.Framework; -using Google.GRPC.Core; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Google.GRPC.Core.Utils; -using System.Collections.Generic; +using Grpc.Core; +using Grpc.Core.Utils; +using NUnit.Framework; namespace math.Tests { diff --git a/src/csharp/GrpcApiTests/Properties/AssemblyInfo.cs b/src/csharp/GrpcApiTests/Properties/AssemblyInfo.cs index 5594e92e72..ac3cfca52e 100644 --- a/src/csharp/GrpcApiTests/Properties/AssemblyInfo.cs +++ b/src/csharp/GrpcApiTests/Properties/AssemblyInfo.cs @@ -8,13 +8,13 @@ using System.Runtime.CompilerServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("jtattermusch")] +[assembly: AssemblyCopyright("Google Inc. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("0.9.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] diff --git a/src/csharp/GrpcCore/Call.cs b/src/csharp/GrpcCore/Call.cs index 93a7507b2f..72dca68895 100644 --- a/src/csharp/GrpcCore/Call.cs +++ b/src/csharp/GrpcCore/Call.cs @@ -32,9 +32,9 @@ #endregion using System; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; -namespace Google.GRPC.Core +namespace Grpc.Core { public class Call<TRequest, TResponse> { diff --git a/src/csharp/GrpcCore/Calls.cs b/src/csharp/GrpcCore/Calls.cs index e5ddd879d6..b67332676a 100644 --- a/src/csharp/GrpcCore/Calls.cs +++ b/src/csharp/GrpcCore/Calls.cs @@ -34,9 +34,9 @@ using System; using System.Threading; using System.Threading.Tasks; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; -namespace Google.GRPC.Core +namespace Grpc.Core { // NOTE: this class is work-in-progress diff --git a/src/csharp/GrpcCore/Channel.cs b/src/csharp/GrpcCore/Channel.cs index d1f795541c..942651cf39 100644 --- a/src/csharp/GrpcCore/Channel.cs +++ b/src/csharp/GrpcCore/Channel.cs @@ -35,9 +35,9 @@ using System; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; -namespace Google.GRPC.Core +namespace Grpc.Core { public class Channel : IDisposable { diff --git a/src/csharp/GrpcCore/ClientStreamingAsyncResult.cs b/src/csharp/GrpcCore/ClientStreamingAsyncResult.cs index f82fe5f26c..44580a1154 100644 --- a/src/csharp/GrpcCore/ClientStreamingAsyncResult.cs +++ b/src/csharp/GrpcCore/ClientStreamingAsyncResult.cs @@ -34,7 +34,7 @@ using System; using System.Threading.Tasks; -namespace Google.GRPC.Core +namespace Grpc.Core { /// <summary> /// Return type for client streaming async method. diff --git a/src/csharp/GrpcCore/GrpcEnvironment.cs b/src/csharp/GrpcCore/GrpcEnvironment.cs index 55a6cac8f6..0e3a0a581c 100644 --- a/src/csharp/GrpcCore/GrpcEnvironment.cs +++ b/src/csharp/GrpcCore/GrpcEnvironment.cs @@ -32,10 +32,10 @@ #endregion using System; -using Google.GRPC.Core.Internal; using System.Runtime.InteropServices; +using Grpc.Core.Internal; -namespace Google.GRPC.Core +namespace Grpc.Core { /// <summary> /// Encapsulates initialization and shutdown of gRPC library. diff --git a/src/csharp/GrpcCore/Internal/AsyncCall.cs b/src/csharp/GrpcCore/Internal/AsyncCall.cs index ce0ba30d53..5e96092e27 100644 --- a/src/csharp/GrpcCore/Internal/AsyncCall.cs +++ b/src/csharp/GrpcCore/Internal/AsyncCall.cs @@ -32,14 +32,14 @@ #endregion using System; -using System.Runtime.InteropServices; using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -using System.Runtime.CompilerServices; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// Handles native call lifecycle and provides convenience methods. @@ -381,7 +381,7 @@ namespace Google.GRPC.Core.Internal private void CompleteStreamObserver(Status status) { - if (status.StatusCode != StatusCode.GRPC_STATUS_OK) + if (status.StatusCode != StatusCode.OK) { // TODO: wrap to handle exceptions; readObserver.OnError(new RpcException(status)); @@ -413,13 +413,13 @@ namespace Google.GRPC.Core.Internal if (error != GRPCOpError.GRPC_OP_OK) { tcs.SetException(new RpcException( - new Status(StatusCode.GRPC_STATUS_INTERNAL, "Internal error occured.") + new Status(StatusCode.Internal, "Internal error occured.") )); return; } var status = ctx.GetReceivedStatus(); - if (status.StatusCode != StatusCode.GRPC_STATUS_OK) + if (status.StatusCode != StatusCode.OK) { tcs.SetException(new RpcException(status)); return; diff --git a/src/csharp/GrpcCore/Internal/BatchContextSafeHandleNotOwned.cs b/src/csharp/GrpcCore/Internal/BatchContextSafeHandleNotOwned.cs index ddfd94a3b5..75cd30e1a2 100644 --- a/src/csharp/GrpcCore/Internal/BatchContextSafeHandleNotOwned.cs +++ b/src/csharp/GrpcCore/Internal/BatchContextSafeHandleNotOwned.cs @@ -33,9 +33,9 @@ using System; using System.Runtime.InteropServices; -using Google.GRPC.Core; +using Grpc.Core; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// Not owned version of diff --git a/src/csharp/GrpcCore/Internal/CallSafeHandle.cs b/src/csharp/GrpcCore/Internal/CallSafeHandle.cs index 55d66a62ca..659a383b4b 100644 --- a/src/csharp/GrpcCore/Internal/CallSafeHandle.cs +++ b/src/csharp/GrpcCore/Internal/CallSafeHandle.cs @@ -32,11 +32,11 @@ #endregion using System; -using System.Runtime.InteropServices; using System.Diagnostics; -using Google.GRPC.Core; +using System.Runtime.InteropServices; +using Grpc.Core; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { //TODO: rename the delegate internal delegate void CompletionCallbackDelegate(GRPCOpError error, IntPtr batchContextPtr); diff --git a/src/csharp/GrpcCore/Internal/ChannelSafeHandle.cs b/src/csharp/GrpcCore/Internal/ChannelSafeHandle.cs index 379c83d537..f15ead3572 100644 --- a/src/csharp/GrpcCore/Internal/ChannelSafeHandle.cs +++ b/src/csharp/GrpcCore/Internal/ChannelSafeHandle.cs @@ -36,7 +36,7 @@ using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// grpc_channel from <grpc/grpc.h> diff --git a/src/csharp/GrpcCore/Internal/ClientStreamingInputObserver.cs b/src/csharp/GrpcCore/Internal/ClientStreamingInputObserver.cs index 4d10a9bdf9..fb59e86e2d 100644 --- a/src/csharp/GrpcCore/Internal/ClientStreamingInputObserver.cs +++ b/src/csharp/GrpcCore/Internal/ClientStreamingInputObserver.cs @@ -32,9 +32,9 @@ #endregion using System; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { internal class ClientStreamingInputObserver<TWrite, TRead> : IObserver<TWrite> { diff --git a/src/csharp/GrpcCore/Internal/CompletionQueueSafeHandle.cs b/src/csharp/GrpcCore/Internal/CompletionQueueSafeHandle.cs index 5ea436df19..3f01fdbfd0 100644 --- a/src/csharp/GrpcCore/Internal/CompletionQueueSafeHandle.cs +++ b/src/csharp/GrpcCore/Internal/CompletionQueueSafeHandle.cs @@ -35,7 +35,7 @@ using System; using System.Runtime.InteropServices; using System.Threading.Tasks; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// grpc_completion_queue from <grpc/grpc.h> diff --git a/src/csharp/GrpcCore/Internal/Enums.cs b/src/csharp/GrpcCore/Internal/Enums.cs index d38896ec84..f363050b07 100644 --- a/src/csharp/GrpcCore/Internal/Enums.cs +++ b/src/csharp/GrpcCore/Internal/Enums.cs @@ -34,7 +34,7 @@ using System; using System.Runtime.InteropServices; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// from grpc/grpc.h diff --git a/src/csharp/GrpcCore/Internal/GrpcThreadPool.cs b/src/csharp/GrpcCore/Internal/GrpcThreadPool.cs index 634a0b2d72..9e69fe2f43 100644 --- a/src/csharp/GrpcCore/Internal/GrpcThreadPool.cs +++ b/src/csharp/GrpcCore/Internal/GrpcThreadPool.cs @@ -32,13 +32,13 @@ #endregion using System; -using Google.GRPC.Core.Internal; +using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -using System.Collections.Generic; +using Grpc.Core.Internal; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// Pool of threads polling on the same completion queue. diff --git a/src/csharp/GrpcCore/Internal/SafeHandleZeroIsInvalid.cs b/src/csharp/GrpcCore/Internal/SafeHandleZeroIsInvalid.cs index 59f08d4ca8..aa6fce2e96 100644 --- a/src/csharp/GrpcCore/Internal/SafeHandleZeroIsInvalid.cs +++ b/src/csharp/GrpcCore/Internal/SafeHandleZeroIsInvalid.cs @@ -34,7 +34,7 @@ using System; using System.Runtime.InteropServices; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// Safe handle to wrap native objects. diff --git a/src/csharp/GrpcCore/Internal/ServerSafeHandle.cs b/src/csharp/GrpcCore/Internal/ServerSafeHandle.cs index 047bde1add..de9bbaf7c1 100644 --- a/src/csharp/GrpcCore/Internal/ServerSafeHandle.cs +++ b/src/csharp/GrpcCore/Internal/ServerSafeHandle.cs @@ -32,11 +32,11 @@ #endregion using System; -using System.Runtime.InteropServices; -using System.Diagnostics; using System.Collections.Concurrent; +using System.Diagnostics; +using System.Runtime.InteropServices; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { // TODO: we need to make sure that the delegates are not collected before invoked. internal delegate void ServerShutdownCallbackDelegate(IntPtr eventPtr); diff --git a/src/csharp/GrpcCore/Internal/ServerStreamingOutputObserver.cs b/src/csharp/GrpcCore/Internal/ServerStreamingOutputObserver.cs index e9cb65cb3b..08d9921475 100644 --- a/src/csharp/GrpcCore/Internal/ServerStreamingOutputObserver.cs +++ b/src/csharp/GrpcCore/Internal/ServerStreamingOutputObserver.cs @@ -32,9 +32,9 @@ #endregion using System; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// Observer that writes all arriving messages to a call abstraction (in blocking fashion) @@ -52,7 +52,7 @@ namespace Google.GRPC.Core.Internal public void OnCompleted() { // TODO: how bad is the Wait here? - call.SendStatusFromServerAsync(new Status(StatusCode.GRPC_STATUS_OK, "")).Wait(); + call.SendStatusFromServerAsync(new Status(StatusCode.OK, "")).Wait(); } public void OnError(Exception error) diff --git a/src/csharp/GrpcCore/Internal/Timespec.cs b/src/csharp/GrpcCore/Internal/Timespec.cs index 38b75180dc..b191ecde94 100644 --- a/src/csharp/GrpcCore/Internal/Timespec.cs +++ b/src/csharp/GrpcCore/Internal/Timespec.cs @@ -35,7 +35,7 @@ using System; using System.Runtime.InteropServices; using System.Threading; -namespace Google.GRPC.Core.Internal +namespace Grpc.Core.Internal { /// <summary> /// gpr_timespec from grpc/support/time.h diff --git a/src/csharp/GrpcCore/Marshaller.cs b/src/csharp/GrpcCore/Marshaller.cs index f031354fd2..602e0eb824 100644 --- a/src/csharp/GrpcCore/Marshaller.cs +++ b/src/csharp/GrpcCore/Marshaller.cs @@ -33,7 +33,7 @@ using System; -namespace Google.GRPC.Core +namespace Grpc.Core { /// <summary> /// For serializing and deserializing messages. diff --git a/src/csharp/GrpcCore/Method.cs b/src/csharp/GrpcCore/Method.cs index 64a4f71396..c94aa8161f 100644 --- a/src/csharp/GrpcCore/Method.cs +++ b/src/csharp/GrpcCore/Method.cs @@ -33,7 +33,7 @@ using System; -namespace Google.GRPC.Core +namespace Grpc.Core { public enum MethodType { diff --git a/src/csharp/GrpcCore/Properties/AssemblyInfo.cs b/src/csharp/GrpcCore/Properties/AssemblyInfo.cs index 0907b86833..ed3a7af8f4 100644 --- a/src/csharp/GrpcCore/Properties/AssemblyInfo.cs +++ b/src/csharp/GrpcCore/Properties/AssemblyInfo.cs @@ -8,13 +8,13 @@ using System.Runtime.CompilerServices; [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] -[assembly: AssemblyCopyright ("jtattermusch")] +[assembly: AssemblyCopyright ("Google Inc. All rights reserved.")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion ("1.0.*")] +[assembly: AssemblyVersion ("0.9.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] diff --git a/src/csharp/GrpcCore/RpcException.cs b/src/csharp/GrpcCore/RpcException.cs index 9ec1d2f2f3..5a9d0039bc 100644 --- a/src/csharp/GrpcCore/RpcException.cs +++ b/src/csharp/GrpcCore/RpcException.cs @@ -33,7 +33,7 @@ using System; -namespace Google.GRPC.Core +namespace Grpc.Core { public class RpcException : Exception { diff --git a/src/csharp/GrpcCore/Server.cs b/src/csharp/GrpcCore/Server.cs index 91842d8182..002592a3d8 100644 --- a/src/csharp/GrpcCore/Server.cs +++ b/src/csharp/GrpcCore/Server.cs @@ -32,14 +32,14 @@ #endregion using System; -using System.Runtime.InteropServices; -using System.Diagnostics; -using System.Threading.Tasks; using System.Collections.Concurrent; using System.Collections.Generic; -using Google.GRPC.Core.Internal; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Grpc.Core.Internal; -namespace Google.GRPC.Core +namespace Grpc.Core { /// <summary> /// Server is implemented only to be able to do diff --git a/src/csharp/GrpcCore/ServerCallHandler.cs b/src/csharp/GrpcCore/ServerCallHandler.cs index 48d1eaa335..1296947f34 100644 --- a/src/csharp/GrpcCore/ServerCallHandler.cs +++ b/src/csharp/GrpcCore/ServerCallHandler.cs @@ -32,9 +32,9 @@ #endregion using System; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; -namespace Google.GRPC.Core +namespace Grpc.Core { internal interface IServerCallHandler { @@ -111,7 +111,7 @@ namespace Google.GRPC.Core var finishedTask = asyncCall.ServerSideStreamingRequestCallAsync(new NullObserver<byte[]>()); - asyncCall.SendStatusFromServerAsync(new Status(StatusCode.GRPC_STATUS_UNIMPLEMENTED, "No such method.")).Wait(); + asyncCall.SendStatusFromServerAsync(new Status(StatusCode.Unimplemented, "No such method.")).Wait(); finishedTask.Wait(); } diff --git a/src/csharp/GrpcCore/ServerCalls.cs b/src/csharp/GrpcCore/ServerCalls.cs index 273029cab6..bed77796de 100644 --- a/src/csharp/GrpcCore/ServerCalls.cs +++ b/src/csharp/GrpcCore/ServerCalls.cs @@ -33,7 +33,7 @@ using System; -namespace Google.GRPC.Core +namespace Grpc.Core { // TODO: perhaps add also serverSideStreaming and clientSideStreaming diff --git a/src/csharp/GrpcCore/ServerServiceDefinition.cs b/src/csharp/GrpcCore/ServerServiceDefinition.cs index 1eb17837e4..231c376062 100644 --- a/src/csharp/GrpcCore/ServerServiceDefinition.cs +++ b/src/csharp/GrpcCore/ServerServiceDefinition.cs @@ -34,7 +34,7 @@ using System; using System.Collections.Generic; -namespace Google.GRPC.Core +namespace Grpc.Core { public class ServerServiceDefinition { diff --git a/src/csharp/GrpcCore/Status.cs b/src/csharp/GrpcCore/Status.cs index 6430e6b7ab..5ea1df7b48 100644 --- a/src/csharp/GrpcCore/Status.cs +++ b/src/csharp/GrpcCore/Status.cs @@ -34,7 +34,7 @@ using System; using System.Runtime.InteropServices; -namespace Google.GRPC.Core +namespace Grpc.Core { /// <summary> /// Represents RPC result. diff --git a/src/csharp/GrpcCore/StatusCode.cs b/src/csharp/GrpcCore/StatusCode.cs index ba99f9b5e0..1fbf9c1b68 100644 --- a/src/csharp/GrpcCore/StatusCode.cs +++ b/src/csharp/GrpcCore/StatusCode.cs @@ -33,22 +33,22 @@ using System; -namespace Google.GRPC.Core +namespace Grpc.Core { // TODO: element names should changed to comply with C# naming conventions. /// <summary> - /// grpc_status_code from grpc/status.h + /// based on grpc_status_code from grpc/status.h /// </summary> public enum StatusCode { /* Not an error; returned on success HTTP Mapping: 200 OK */ - GRPC_STATUS_OK = 0, + OK = 0, /* The operation was cancelled (typically by the caller). HTTP Mapping: 499 Client Closed Request */ - GRPC_STATUS_CANCELLED = 1, + Cancelled = 1, /* Unknown error. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known in this address space. Also @@ -56,14 +56,14 @@ namespace Google.GRPC.Core may be converted to this error. HTTP Mapping: 500 Internal Server Error */ - GRPC_STATUS_UNKNOWN = 2, + Unknown = 2, /* Client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name). HTTP Mapping: 400 Bad Request */ - GRPC_STATUS_INVALID_ARGUMENT = 3, + InvalidArgument = 3, /* Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a @@ -71,16 +71,16 @@ namespace Google.GRPC.Core enough for the deadline to expire. HTTP Mapping: 504 Gateway Timeout */ - GRPC_STATUS_DEADLINE_EXCEEDED = 4, + DeadlineExceeded = 4, /* Some requested entity (e.g., file or directory) was not found. HTTP Mapping: 404 Not Found */ - GRPC_STATUS_NOT_FOUND = 5, + NotFound = 5, /* Some entity that we attempted to create (e.g., file or directory) already exists. HTTP Mapping: 409 Conflict */ - GRPC_STATUS_ALREADY_EXISTS = 6, + AlreadyExists = 6, /* The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED @@ -89,17 +89,17 @@ namespace Google.GRPC.Core instead for those errors). HTTP Mapping: 403 Forbidden */ - GRPC_STATUS_PERMISSION_DENIED = 7, + PermissionDenied = 7, /* The request does not have valid authentication credentials for the operation. HTTP Mapping: 401 Unauthorized */ - GRPC_STATUS_UNAUTHENTICATED = 16, + Unauthenticated = 16, /* Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. HTTP Mapping: 429 Too Many Requests */ - GRPC_STATUS_RESOURCE_EXHAUSTED = 8, + ResourceExhausted = 8, /* Operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to @@ -126,7 +126,7 @@ namespace Google.GRPC.Core the request contains Etag related headers. So if the server does see Etag related headers in the request, it may choose to return 412 instead of 400 for this error code. */ - GRPC_STATUS_FAILED_PRECONDITION = 9, + FailedPrecondition = 9, /* The operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc. @@ -134,7 +134,7 @@ namespace Google.GRPC.Core ABORTED, and UNAVAILABLE. HTTP Mapping: 409 Conflict */ - GRPC_STATUS_ABORTED = 10, + Aborted = 10, /* Operation was attempted past the valid range. E.g., seeking or reading past end of file. @@ -152,17 +152,17 @@ namespace Google.GRPC.Core they are done. HTTP Mapping: 400 Bad Request */ - GRPC_STATUS_OUT_OF_RANGE = 11, + OutOfRange = 11, /* Operation is not implemented or not supported/enabled in this service. HTTP Mapping: 501 Not Implemented */ - GRPC_STATUS_UNIMPLEMENTED = 12, + Unimplemented = 12, /* Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken. HTTP Mapping: 500 Internal Server Error */ - GRPC_STATUS_INTERNAL = 13, + Internal = 13, /* The service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. @@ -171,13 +171,11 @@ namespace Google.GRPC.Core ABORTED, and UNAVAILABLE. HTTP Mapping: 503 Service Unavailable */ - GRPC_STATUS_UNAVAILABLE = 14, + Unavailable = 14, /* Unrecoverable data loss or corruption. HTTP Mapping: 500 Internal Server Error */ - GRPC_STATUS_DATA_LOSS = 15, - /* Force users to include a default branch: */ - GRPC_STATUS__DO_NOT_USE = -1 + DataLoss = 15 } } diff --git a/src/csharp/GrpcCore/Utils/RecordingObserver.cs b/src/csharp/GrpcCore/Utils/RecordingObserver.cs index 0c784e1d35..99d2725b70 100644 --- a/src/csharp/GrpcCore/Utils/RecordingObserver.cs +++ b/src/csharp/GrpcCore/Utils/RecordingObserver.cs @@ -32,10 +32,10 @@ #endregion using System; -using System.Threading.Tasks; using System.Collections.Generic; +using System.Threading.Tasks; -namespace Google.GRPC.Core.Utils +namespace Grpc.Core.Utils { public class RecordingObserver<T> : IObserver<T> { diff --git a/src/csharp/GrpcCore/Utils/RecordingQueue.cs b/src/csharp/GrpcCore/Utils/RecordingQueue.cs index f8940d7584..63992da6a9 100644 --- a/src/csharp/GrpcCore/Utils/RecordingQueue.cs +++ b/src/csharp/GrpcCore/Utils/RecordingQueue.cs @@ -36,7 +36,7 @@ using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.Concurrent; -namespace Google.GRPC.Core.Utils +namespace Grpc.Core.Utils { // TODO: replace this by something that implements IAsyncEnumerator. /// <summary> diff --git a/src/csharp/GrpcCoreTests/ClientServerTest.cs b/src/csharp/GrpcCoreTests/ClientServerTest.cs index ba43e4f6a0..7e564a2fba 100644 --- a/src/csharp/GrpcCoreTests/ClientServerTest.cs +++ b/src/csharp/GrpcCoreTests/ClientServerTest.cs @@ -32,15 +32,15 @@ #endregion using System; -using NUnit.Framework; -using Google.GRPC.Core; -using Google.GRPC.Core.Internal; -using System.Threading; using System.Diagnostics; +using System.Threading; using System.Threading.Tasks; -using Google.GRPC.Core.Utils; +using Grpc.Core; +using Grpc.Core.Internal; +using Grpc.Core.Utils; +using NUnit.Framework; -namespace Google.GRPC.Core.Tests +namespace Grpc.Core.Tests { public class ClientServerTest { @@ -133,7 +133,7 @@ namespace Google.GRPC.Core.Tests Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)); Assert.Fail(); } catch(RpcException e) { - Assert.AreEqual(StatusCode.GRPC_STATUS_UNIMPLEMENTED, e.Status.StatusCode); + Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode); } } diff --git a/src/csharp/GrpcCoreTests/GrpcEnvironmentTest.cs b/src/csharp/GrpcCoreTests/GrpcEnvironmentTest.cs index 8656b1bf01..8d3aef946a 100644 --- a/src/csharp/GrpcCoreTests/GrpcEnvironmentTest.cs +++ b/src/csharp/GrpcCoreTests/GrpcEnvironmentTest.cs @@ -32,11 +32,11 @@ #endregion using System; -using NUnit.Framework; -using Google.GRPC.Core; using System.Threading; +using Grpc.Core; +using NUnit.Framework; -namespace Google.GRPC.Core.Tests +namespace Grpc.Core.Tests { public class GrpcEnvironmentTest { diff --git a/src/csharp/GrpcCoreTests/Properties/AssemblyInfo.cs b/src/csharp/GrpcCoreTests/Properties/AssemblyInfo.cs index a93d843889..07f35556df 100644 --- a/src/csharp/GrpcCoreTests/Properties/AssemblyInfo.cs +++ b/src/csharp/GrpcCoreTests/Properties/AssemblyInfo.cs @@ -8,13 +8,13 @@ using System.Runtime.CompilerServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("jtattermusch")] +[assembly: AssemblyCopyright("Google Inc. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("0.9.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] diff --git a/src/csharp/GrpcCoreTests/ServerTest.cs b/src/csharp/GrpcCoreTests/ServerTest.cs index 43414a4cc4..dd30366f6a 100644 --- a/src/csharp/GrpcCoreTests/ServerTest.cs +++ b/src/csharp/GrpcCoreTests/ServerTest.cs @@ -32,12 +32,12 @@ #endregion using System; +using Grpc.Core; +using Grpc.Core.Internal; +using Grpc.Core.Utils; using NUnit.Framework; -using Google.GRPC.Core.Internal; -using Google.GRPC.Core; -using Google.GRPC.Core.Utils; -namespace Google.GRPC.Core.Tests +namespace Grpc.Core.Tests { public class ServerTest { @@ -47,7 +47,7 @@ namespace Google.GRPC.Core.Tests GrpcEnvironment.Initialize(); Server server = new Server(); - int port = server.AddPort("localhost:0"); + server.AddPort("localhost:0"); server.Start(); server.ShutdownAsync().Wait(); diff --git a/src/csharp/GrpcCoreTests/TestResult.xml b/src/csharp/GrpcCoreTests/TestResult.xml index a5a6abd7b9..13da80739c 100644 --- a/src/csharp/GrpcCoreTests/TestResult.xml +++ b/src/csharp/GrpcCoreTests/TestResult.xml @@ -15,17 +15,17 @@ <results> <test-suite type="TestFixture" name="CallsTest" executed="True" result="Success" success="True" time="0.009" asserts="0"> <results> - <test-case name="Google.GRPC.Core.Tests.CallsTest.Test1" executed="True" result="Success" success="True" time="0.004" asserts="0" /> + <test-case name="Grpc.Core.Tests.CallsTest.Test1" executed="True" result="Success" success="True" time="0.004" asserts="0" /> </results> </test-suite> <test-suite type="TestFixture" name="ClientServerTest" executed="True" result="Success" success="True" time="0.149" asserts="0"> <results> - <test-case name="Google.GRPC.Core.Tests.ClientServerTest.EmptyCall" executed="True" result="Success" success="True" time="0.111" asserts="0" /> + <test-case name="Grpc.Core.Tests.ClientServerTest.EmptyCall" executed="True" result="Success" success="True" time="0.111" asserts="0" /> </results> </test-suite> <test-suite type="TestFixture" name="ServerTest" executed="True" result="Success" success="True" time="0.001" asserts="0"> <results> - <test-case name="Google.GRPC.Core.Tests.ServerTest.StartAndShutdownServer" executed="True" result="Success" success="True" time="0.001" asserts="0" /> + <test-case name="Grpc.Core.Tests.ServerTest.StartAndShutdownServer" executed="True" result="Success" success="True" time="0.001" asserts="0" /> </results> </test-suite> </results> diff --git a/src/csharp/GrpcCoreTests/TimespecTest.cs b/src/csharp/GrpcCoreTests/TimespecTest.cs index 2169824219..0ca84ec44b 100644 --- a/src/csharp/GrpcCoreTests/TimespecTest.cs +++ b/src/csharp/GrpcCoreTests/TimespecTest.cs @@ -32,11 +32,11 @@ #endregion using System; -using NUnit.Framework; using System.Runtime.InteropServices; -using Google.GRPC.Core.Internal; +using Grpc.Core.Internal; +using NUnit.Framework; -namespace Google.GRPC.Core.Internal.Tests +namespace Grpc.Core.Internal.Tests { public class TimespecTest { diff --git a/src/csharp/InteropClient/Client.cs b/src/csharp/InteropClient/Client.cs index 945afe0642..fdec6efd2e 100644 --- a/src/csharp/InteropClient/Client.cs +++ b/src/csharp/InteropClient/Client.cs @@ -33,14 +33,14 @@ using System; using System.Collections.Generic; -using NUnit.Framework; using System.Text.RegularExpressions; -using Google.GRPC.Core; -using Google.GRPC.Core.Utils; using Google.ProtocolBuffers; +using Grpc.Core; +using Grpc.Core.Utils; +using NUnit.Framework; using grpc.testing; -namespace Google.GRPC.Interop +namespace Grpc.Interop { class Client { diff --git a/src/csharp/InteropClient/InteropClient.csproj b/src/csharp/InteropClient/InteropClient.csproj index a450f3a2fe..29590f4950 100644 --- a/src/csharp/InteropClient/InteropClient.csproj +++ b/src/csharp/InteropClient/InteropClient.csproj @@ -9,7 +9,7 @@ <OutputType>Exe</OutputType> <RootNamespace>InteropClient</RootNamespace> <AssemblyName>InteropClient</AssemblyName> - <StartupObject>Google.GRPC.Interop.Client</StartupObject> + <StartupObject>Grpc.Interop.Client</StartupObject> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> @@ -33,14 +33,13 @@ <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <ItemGroup> - <Reference Include="Google.ProtocolBuffers, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\Google.ProtocolBuffers.2.4.1.521\lib\net40\Google.ProtocolBuffers.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> </ItemGroup> <ItemGroup> <Compile Include="Properties\AssemblyInfo.cs" /> diff --git a/src/csharp/InteropClient/Properties/AssemblyInfo.cs b/src/csharp/InteropClient/Properties/AssemblyInfo.cs index 00b4bd5895..3a13173ac7 100644 --- a/src/csharp/InteropClient/Properties/AssemblyInfo.cs +++ b/src/csharp/InteropClient/Properties/AssemblyInfo.cs @@ -8,13 +8,13 @@ using System.Runtime.CompilerServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("jtattermusch")] +[assembly: AssemblyCopyright("Google Inc. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("0.9.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] diff --git a/src/csharp/MathClient/MathClient.cs b/src/csharp/MathClient/MathClient.cs index eb9b7b105b..95a4678bb8 100644 --- a/src/csharp/MathClient/MathClient.cs +++ b/src/csharp/MathClient/MathClient.cs @@ -33,8 +33,8 @@ using System; using System.Runtime.InteropServices; -using Google.GRPC.Core; using System.Threading; +using Grpc.Core; namespace math { diff --git a/src/csharp/MathClient/Properties/AssemblyInfo.cs b/src/csharp/MathClient/Properties/AssemblyInfo.cs index aa614943ac..d24412f497 100644 --- a/src/csharp/MathClient/Properties/AssemblyInfo.cs +++ b/src/csharp/MathClient/Properties/AssemblyInfo.cs @@ -8,13 +8,13 @@ using System.Runtime.CompilerServices; [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] -[assembly: AssemblyCopyright ("jtattermusch")] +[assembly: AssemblyCopyright ("Google Inc. All rights reserved.")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion ("1.0.*")] +[assembly: AssemblyVersion ("0.9.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] diff --git a/src/csharp/README.md b/src/csharp/README.md index f56ddabda5..9967af22b3 100755 --- a/src/csharp/README.md +++ b/src/csharp/README.md @@ -1,9 +1,9 @@ gRPC C# ======= -A C# implementation of gRPC, Google's RPC library. +A C# implementation of gRPC. -EXPERIMENTAL ONLY +Status ----------------- **This gRPC C# implementation is work-in-progress and is not expected to work yet.** diff --git a/src/node/.jshintrc b/src/node/.jshintrc new file mode 100644 index 0000000000..8237e0d2b6 --- /dev/null +++ b/src/node/.jshintrc @@ -0,0 +1,28 @@ +{ + "bitwise": true, + "curly": true, + "eqeqeq": true, + "esnext": true, + "freeze": true, + "immed": true, + "indent": 2, + "latedef": "nofunc", + "maxlen": 80, + "newcap": true, + "node": true, + "noarg": true, + "quotmark": "single", + "strict": true, + "trailing": true, + "undef": true, + "unused": "vars", + "globals": { + /* Mocha-provided globals */ + "describe": false, + "it": false, + "before": false, + "beforeEach": false, + "after": false, + "afterEach": false + } +} diff --git a/src/node/README.md b/src/node/README.md index c342b7ca57..8880213e9a 100644 --- a/src/node/README.md +++ b/src/node/README.md @@ -1,5 +1,9 @@ # Node.js gRPC Library +## Status + +Alpha : Ready for early adopters + ## Installation First, clone this repository (NPM package coming soon). Then follow the instructions in the `INSTALL` file in the root of the repository to install the C core library that this package depends on. diff --git a/src/node/examples/math_server.js b/src/node/examples/math_server.js index 89bc0de3ba..ae548c89e4 100644 --- a/src/node/examples/math_server.js +++ b/src/node/examples/math_server.js @@ -31,9 +31,8 @@ * */ -var _ = require('underscore'); -var ProtoBuf = require('protobufjs'); -var fs = require('fs'); +'use strict'; + var util = require('util'); var Transform = require('stream').Transform; diff --git a/src/node/examples/perf_test.js b/src/node/examples/perf_test.js index c5e2872736..31083e0987 100644 --- a/src/node/examples/perf_test.js +++ b/src/node/examples/perf_test.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var grpc = require('..'); var testProto = grpc.load(__dirname + '/../interop/test.proto').grpc.testing; var _ = require('underscore'); @@ -44,7 +46,6 @@ function runTest(iterations, callback) { function runIterations(finish) { var start = process.hrtime(); var intervals = []; - var pending = iterations; function next(i) { if (i >= iterations) { testServer.server.shutdown(); @@ -69,28 +70,30 @@ function runTest(iterations, callback) { function warmUp(num) { var pending = num; + function startCall() { + client.emptyCall({}, function(err, resp) { + pending--; + if (pending === 0) { + runIterations(callback); + } + }); + } for (var i = 0; i < num; i++) { - (function(i) { - client.emptyCall({}, function(err, resp) { - pending--; - if (pending === 0) { - runIterations(callback); - } - }); - })(i); + startCall(); } } warmUp(100); } -function percentile(arr, percentile) { - if (percentile > 99) { - percentile = 99; +function percentile(arr, pct) { + if (pct > 99) { + pct = 99; } - if (percentile < 0) { - percentile = 0; + if (pct < 0) { + pct = 0; } - return arr[(arr.length * percentile / 100)|0]; + var index = Math.floor(arr.length * pct / 100); + return arr[index]; } if (require.main === module) { diff --git a/src/node/examples/stock_server.js b/src/node/examples/stock_server.js index b226a71573..e475c9cb4c 100644 --- a/src/node/examples/stock_server.js +++ b/src/node/examples/stock_server.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var _ = require('underscore'); var grpc = require('..'); var examples = grpc.load(__dirname + '/stock.proto').examples; diff --git a/src/node/ext/node_grpc.cc b/src/node/ext/node_grpc.cc index 965186e0cc..9f5095839c 100644 --- a/src/node/ext/node_grpc.cc +++ b/src/node/ext/node_grpc.cc @@ -38,7 +38,6 @@ #include "call.h" #include "channel.h" -#include "event.h" #include "server.h" #include "completion_queue_async_worker.h" #include "credentials.h" diff --git a/src/node/index.js b/src/node/index.js index 1bef2072dd..4b5302e438 100644 --- a/src/node/index.js +++ b/src/node/index.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var _ = require('underscore'); var ProtoBuf = require('protobufjs'); diff --git a/src/node/interop/interop_client.js b/src/node/interop/interop_client.js index fc2fdf4dc9..eaf254bcfe 100644 --- a/src/node/interop/interop_client.js +++ b/src/node/interop/interop_client.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var fs = require('fs'); var path = require('path'); var grpc = require('..'); @@ -41,7 +43,8 @@ var assert = require('assert'); var AUTH_SCOPE = 'https://www.googleapis.com/auth/xapi.zoo'; var AUTH_SCOPE_RESPONSE = 'xapi.zoo'; -var AUTH_USER = '155450119199-3psnrh1sdr3d8cpj1v46naggf81mhdnk@developer.gserviceaccount.com'; +var AUTH_USER = ('155450119199-3psnrh1sdr3d8cpj1v46naggf81mhdnk' + + '@developer.gserviceaccount.com'); /** * Create a buffer filled with size zeroes @@ -318,7 +321,7 @@ var test_cases = { /** * Execute a single test case. * @param {string} address The address of the server to connect to, in the - * format "hostname:port" + * format 'hostname:port' * @param {string} host_overrirde The hostname of the server to use as an SSL * override * @param {string} test_case The name of the test case to run diff --git a/src/node/interop/interop_server.js b/src/node/interop/interop_server.js index c97d234455..125ede1746 100644 --- a/src/node/interop/interop_server.js +++ b/src/node/interop/interop_server.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var fs = require('fs'); var path = require('path'); var _ = require('underscore'); diff --git a/src/node/package.json b/src/node/package.json index 821641ce19..a71577fb96 100644 --- a/src/node/package.json +++ b/src/node/package.json @@ -3,10 +3,12 @@ "version": "0.2.0", "description": "gRPC Library for Node", "scripts": { - "test": "./node_modules/mocha/bin/mocha" + "lint": "nodejs ./node_modules/jshint/bin/jshint src test examples interop index.js", + "test": "nodejs ./node_modules/mocha/bin/mocha && npm run-script lint" }, "dependencies": { "bindings": "^1.2.1", + "jshint": "^2.5.5", "nan": "~1.3.0", "protobufjs": "murgatroid99/ProtoBuf.js", "underscore": "^1.7.0", @@ -17,5 +19,15 @@ "minimist": "^1.1.0", "googleauth": "google/google-auth-library-nodejs" }, + "files": [ + "README.md", + "index.js", + "binding.gyp", + "examples", + "ext", + "interop", + "src", + "test" + ], "main": "index.js" } diff --git a/src/node/src/client.js b/src/node/src/client.js index 19c3144c7d..aaa7be79c9 100644 --- a/src/node/src/client.js +++ b/src/node/src/client.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var _ = require('underscore'); var capitalize = require('underscore.string/capitalize'); @@ -77,6 +79,7 @@ function ClientWritableStream(call, serialize) { * @param {function(Error=)} callback Called when the write is complete */ function _write(chunk, encoding, callback) { + /* jshint validthis: true */ var batch = {}; batch[grpc.opType.SEND_MESSAGE] = this.serialize(chunk); this.call.startBatch(batch, function(err, event) { @@ -85,7 +88,7 @@ function _write(chunk, encoding, callback) { } callback(); }); -}; +} ClientWritableStream.prototype._write = _write; @@ -111,6 +114,7 @@ function ClientReadableStream(call, deserialize) { * @param {*} size Ignored because we use objectMode=true */ function _read(size) { + /* jshint validthis: true */ var self = this; /** * Callback to be called when a READ event is received. Pushes the data onto @@ -126,7 +130,7 @@ function _read(size) { return; } var data = event.read; - if (self.push(self.deserialize(data)) && data != null) { + if (self.push(self.deserialize(data)) && data !== null) { var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(read_batch, readCallback); @@ -144,7 +148,7 @@ function _read(size) { self.call.startBatch(read_batch, readCallback); } } -}; +} ClientReadableStream.prototype._read = _read; @@ -163,10 +167,6 @@ function ClientDuplexStream(call, serialize, deserialize) { Duplex.call(this, {objectMode: true}); this.serialize = common.wrapIgnoreNull(serialize); this.deserialize = common.wrapIgnoreNull(deserialize); - var self = this; - var finished = false; - // Indicates that a read is currently pending - var reading = false; this.call = call; this.on('finish', function() { var batch = {}; @@ -182,6 +182,7 @@ ClientDuplexStream.prototype._write = _write; * Cancel the ongoing call */ function cancel() { + /* jshint validthis: true */ this.call.cancel(); } @@ -213,6 +214,7 @@ function makeUnaryRequestFunction(method, serialize, deserialize) { * @return {EventEmitter} An event emitter for stream related events */ function makeUnaryRequest(argument, callback, metadata, deadline) { + /* jshint validthis: true */ if (deadline === undefined) { deadline = Infinity; } @@ -242,7 +244,7 @@ function makeUnaryRequestFunction(method, serialize, deserialize) { callback(err); return; } - if (response.status.code != grpc.status.OK) { + if (response.status.code !== grpc.status.OK) { callback(response.status); return; } @@ -278,6 +280,7 @@ function makeClientStreamRequestFunction(method, serialize, deserialize) { * @return {EventEmitter} An event emitter for stream related events */ function makeClientStreamRequest(callback, metadata, deadline) { + /* jshint validthis: true */ if (deadline === undefined) { deadline = Infinity; } @@ -310,7 +313,7 @@ function makeClientStreamRequestFunction(method, serialize, deserialize) { callback(err); return; } - if (response.status.code != grpc.status.OK) { + if (response.status.code !== grpc.status.OK) { callback(response.status); return; } @@ -345,6 +348,7 @@ function makeServerStreamRequestFunction(method, serialize, deserialize) { * @return {EventEmitter} An event emitter for stream related events */ function makeServerStreamRequest(argument, metadata, deadline) { + /* jshint validthis: true */ if (deadline === undefined) { deadline = Infinity; } @@ -404,6 +408,7 @@ function makeBidiStreamRequestFunction(method, serialize, deserialize) { * @return {EventEmitter} An event emitter for stream related events */ function makeBidiStreamRequest(metadata, deadline) { + /* jshint validthis: true */ if (deadline === undefined) { deadline = Infinity; } diff --git a/src/node/src/common.js b/src/node/src/common.js index 848c96742d..eec8f0f987 100644 --- a/src/node/src/common.js +++ b/src/node/src/common.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var _ = require('underscore'); var capitalize = require('underscore.string/capitalize'); diff --git a/src/node/src/server.js b/src/node/src/server.js index 48c349ef99..91dde02251 100644 --- a/src/node/src/server.js +++ b/src/node/src/server.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var _ = require('underscore'); var capitalize = require('underscore.string/capitalize'); @@ -217,6 +219,7 @@ function ServerWritableStream(call, serialize) { * complete */ function _write(chunk, encoding, callback) { + /* jshint validthis: true */ var batch = {}; batch[grpc.opType.SEND_MESSAGE] = this.serialize(chunk); this.call.startBatch(batch, function(err, value) { @@ -251,6 +254,7 @@ function ServerReadableStream(call, deserialize) { * @param {number} size Ignored */ function _read(size) { + /* jshint validthis: true */ var self = this; /** * Callback to be called when a READ event is received. Pushes the data onto @@ -267,7 +271,7 @@ function _read(size) { return; } var data = event.read; - if (self.push(self.deserialize(data)) && data != null) { + if (self.push(self.deserialize(data)) && data !== null) { var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(read_batch, readCallback); @@ -424,7 +428,6 @@ function Server(getMetadata, options) { var handlers = this.handlers; var server = new grpc.Server(options); this._server = server; - var started = false; /** * Start the server and begin handling requests * @this Server @@ -456,8 +459,7 @@ function Server(getMetadata, options) { return; } server.requestCall(handleNewCall); - var handler = undefined; - var deadline = details.deadline; + var handler; if (handlers.hasOwnProperty(method)) { handler = handlers[method]; } else { @@ -465,7 +467,7 @@ function Server(getMetadata, options) { batch[grpc.opType.SEND_INITIAL_METADATA] = {}; batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { code: grpc.status.UNIMPLEMENTED, - details: "This method is not available on this server.", + details: 'This method is not available on this server.', metadata: {} }; batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; diff --git a/src/node/test/call_test.js b/src/node/test/call_test.js index c1a7e95fa0..7b2b36ae37 100644 --- a/src/node/test/call_test.js +++ b/src/node/test/call_test.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var assert = require('assert'); var grpc = require('bindings')('grpc.node'); diff --git a/src/node/test/channel_test.js b/src/node/test/channel_test.js index 449a8cc4c3..33200c99ee 100644 --- a/src/node/test/channel_test.js +++ b/src/node/test/channel_test.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var assert = require('assert'); var grpc = require('bindings')('grpc.node'); diff --git a/src/node/test/constant_test.js b/src/node/test/constant_test.js index 4a403868c7..ecc98ec443 100644 --- a/src/node/test/constant_test.js +++ b/src/node/test/constant_test.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var assert = require('assert'); var grpc = require('bindings')('grpc.node'); diff --git a/src/node/test/end_to_end_test.js b/src/node/test/end_to_end_test.js index 8e99d6f162..1cc1928691 100644 --- a/src/node/test/end_to_end_test.js +++ b/src/node/test/end_to_end_test.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var assert = require('assert'); var grpc = require('bindings')('grpc.node'); @@ -227,7 +229,7 @@ describe('end-to-end', function() { response_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; server_call.startBatch(response_batch, function(err, response) { assert(response['send status']); - assert(!response['cancelled']); + assert(!response.cancelled); done(); }); }); diff --git a/src/node/test/interop_sanity_test.js b/src/node/test/interop_sanity_test.js index d1bdd1660f..8dc933eac5 100644 --- a/src/node/test/interop_sanity_test.js +++ b/src/node/test/interop_sanity_test.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var interop_server = require('../interop/interop_server.js'); var interop_client = require('../interop/interop_client.js'); diff --git a/src/node/test/math_client_test.js b/src/node/test/math_client_test.js index fd946e0325..d83f64116f 100644 --- a/src/node/test/math_client_test.js +++ b/src/node/test/math_client_test.js @@ -31,6 +31,8 @@ * */ +'use strict'; + var assert = require('assert'); var grpc = require('..'); @@ -59,7 +61,7 @@ describe('Math client', function() { }); it('should handle a single request', function(done) { var arg = {dividend: 7, divisor: 4}; - var call = math_client.div(arg, function handleDivResult(err, value) { + math_client.div(arg, function handleDivResult(err, value) { assert.ifError(err); assert.equal(value.quotient, 1); assert.equal(value.remainder, 3); diff --git a/src/node/test/surface_test.js b/src/node/test/surface_test.js index d6694724e5..91d8197bee 100644 --- a/src/node/test/surface_test.js +++ b/src/node/test/surface_test.js @@ -31,9 +31,9 @@ * */ -var assert = require('assert'); +'use strict'; -var surface_server = require('../src/server.js'); +var assert = require('assert'); var surface_client = require('../src/client.js'); diff --git a/src/objective-c/GRPCClient/GRPCCall.h b/src/objective-c/GRPCClient/GRPCCall.h index 10437cb8bc..3a18db6137 100644 --- a/src/objective-c/GRPCClient/GRPCCall.h +++ b/src/objective-c/GRPCClient/GRPCCall.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/GRPCCall.m b/src/objective-c/GRPCClient/GRPCCall.m index 46a1e232e3..f246b81e63 100644 --- a/src/objective-c/GRPCClient/GRPCCall.m +++ b/src/objective-c/GRPCClient/GRPCCall.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/GRPCMethodName.h b/src/objective-c/GRPCClient/GRPCMethodName.h index a62c479788..dcad8a3347 100644 --- a/src/objective-c/GRPCClient/GRPCMethodName.h +++ b/src/objective-c/GRPCClient/GRPCMethodName.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/GRPCMethodName.m b/src/objective-c/GRPCClient/GRPCMethodName.m index fbaf24b9f0..96724073a5 100644 --- a/src/objective-c/GRPCClient/GRPCMethodName.m +++ b/src/objective-c/GRPCClient/GRPCMethodName.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/GRPCChannel.h b/src/objective-c/GRPCClient/private/GRPCChannel.h index 7442f1fae4..2e07dcc3c7 100644 --- a/src/objective-c/GRPCClient/private/GRPCChannel.h +++ b/src/objective-c/GRPCClient/private/GRPCChannel.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/GRPCChannel.m b/src/objective-c/GRPCClient/private/GRPCChannel.m index 3e6952cfa3..c8fa69ef91 100644 --- a/src/objective-c/GRPCClient/private/GRPCChannel.m +++ b/src/objective-c/GRPCClient/private/GRPCChannel.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h b/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h index 0a8e397443..c85d57c0ea 100644 --- a/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h +++ b/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/GRPCCompletionQueue.m b/src/objective-c/GRPCClient/private/GRPCCompletionQueue.m index c81e9a2a98..bc2a824a6b 100644 --- a/src/objective-c/GRPCClient/private/GRPCCompletionQueue.m +++ b/src/objective-c/GRPCClient/private/GRPCCompletionQueue.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.h b/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.h index b8a73b12df..24c2b96729 100644 --- a/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.h +++ b/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.m b/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.m index 73a2f51f1b..2a3a50f763 100644 --- a/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.m +++ b/src/objective-c/GRPCClient/private/GRPCDelegateWrapper.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -33,7 +33,7 @@ #import "GRPCDelegateWrapper.h" -#import <net/grpc/objc/RxLibrary/GRXWriteable.h> +#import <RxLibrary/GRXWriteable.h> @interface GRPCDelegateWrapper () // These are atomic so that cancellation can nillify them from any thread. diff --git a/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.h b/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.h index 05e35bb1a3..28c7374517 100644 --- a/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.h +++ b/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.m b/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.m index 3fb9af25ec..3ad757fb29 100644 --- a/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.m +++ b/src/objective-c/GRPCClient/private/GRPCMethodName+HTTP2Encoding.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/NSData+GRPC.h b/src/objective-c/GRPCClient/private/NSData+GRPC.h index 936c2a0e8a..65ac151c2e 100644 --- a/src/objective-c/GRPCClient/private/NSData+GRPC.h +++ b/src/objective-c/GRPCClient/private/NSData+GRPC.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/NSData+GRPC.m b/src/objective-c/GRPCClient/private/NSData+GRPC.m index b5f952722c..f885e9db9c 100644 --- a/src/objective-c/GRPCClient/private/NSData+GRPC.m +++ b/src/objective-c/GRPCClient/private/NSData+GRPC.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/NSDictionary+GRPC.h b/src/objective-c/GRPCClient/private/NSDictionary+GRPC.h index bf0233fd46..8025285259 100644 --- a/src/objective-c/GRPCClient/private/NSDictionary+GRPC.h +++ b/src/objective-c/GRPCClient/private/NSDictionary+GRPC.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/NSDictionary+GRPC.m b/src/objective-c/GRPCClient/private/NSDictionary+GRPC.m index 345ff3e1e6..e59685e4a8 100644 --- a/src/objective-c/GRPCClient/private/NSDictionary+GRPC.m +++ b/src/objective-c/GRPCClient/private/NSDictionary+GRPC.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/NSError+GRPC.h b/src/objective-c/GRPCClient/private/NSError+GRPC.h index b7439fa067..6183008983 100644 --- a/src/objective-c/GRPCClient/private/NSError+GRPC.h +++ b/src/objective-c/GRPCClient/private/NSError+GRPC.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/GRPCClient/private/NSError+GRPC.m b/src/objective-c/GRPCClient/private/NSError+GRPC.m index 4fc1249efc..15c0208681 100644 --- a/src/objective-c/GRPCClient/private/NSError+GRPC.m +++ b/src/objective-c/GRPCClient/private/NSError+GRPC.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXImmediateWriter.h b/src/objective-c/RxLibrary/GRXImmediateWriter.h index 74f4dc69f4..f86d38dcd8 100644 --- a/src/objective-c/RxLibrary/GRXImmediateWriter.h +++ b/src/objective-c/RxLibrary/GRXImmediateWriter.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXImmediateWriter.m b/src/objective-c/RxLibrary/GRXImmediateWriter.m index 4417ae8f16..7468af557f 100644 --- a/src/objective-c/RxLibrary/GRXImmediateWriter.m +++ b/src/objective-c/RxLibrary/GRXImmediateWriter.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriteable.h b/src/objective-c/RxLibrary/GRXWriteable.h index 5aa00ba40e..cdcb99f459 100644 --- a/src/objective-c/RxLibrary/GRXWriteable.h +++ b/src/objective-c/RxLibrary/GRXWriteable.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriteable.m b/src/objective-c/RxLibrary/GRXWriteable.m index 9567e42b74..7231f06462 100644 --- a/src/objective-c/RxLibrary/GRXWriteable.m +++ b/src/objective-c/RxLibrary/GRXWriteable.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriter+Immediate.h b/src/objective-c/RxLibrary/GRXWriter+Immediate.h index 101df81e5e..b75c0a5a64 100644 --- a/src/objective-c/RxLibrary/GRXWriter+Immediate.h +++ b/src/objective-c/RxLibrary/GRXWriter+Immediate.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriter+Immediate.m b/src/objective-c/RxLibrary/GRXWriter+Immediate.m index 7dab5e2ba5..39c54f86ec 100644 --- a/src/objective-c/RxLibrary/GRXWriter+Immediate.m +++ b/src/objective-c/RxLibrary/GRXWriter+Immediate.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriter+Transformations.h b/src/objective-c/RxLibrary/GRXWriter+Transformations.h index cfd644b520..60c4da37d6 100644 --- a/src/objective-c/RxLibrary/GRXWriter+Transformations.h +++ b/src/objective-c/RxLibrary/GRXWriter+Transformations.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriter+Transformations.m b/src/objective-c/RxLibrary/GRXWriter+Transformations.m index 67c54a7e80..d37ed308cc 100644 --- a/src/objective-c/RxLibrary/GRXWriter+Transformations.m +++ b/src/objective-c/RxLibrary/GRXWriter+Transformations.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriter.h b/src/objective-c/RxLibrary/GRXWriter.h index 8bda52fcb9..68c294f007 100644 --- a/src/objective-c/RxLibrary/GRXWriter.h +++ b/src/objective-c/RxLibrary/GRXWriter.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/GRXWriter.m b/src/objective-c/RxLibrary/GRXWriter.m index 7d6c2acd36..b48a44f3a7 100644 --- a/src/objective-c/RxLibrary/GRXWriter.m +++ b/src/objective-c/RxLibrary/GRXWriter.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h index e3f8bbe9c2..400e834c6a 100644 --- a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h +++ b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m index 807a1cd700..5fc81e3292 100644 --- a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m +++ b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h index 4253324e95..34cfc4d8a7 100644 --- a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h +++ b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m index 53b8bb863d..163e310bcf 100644 --- a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m +++ b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.h b/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.h index 1c28b158d7..1565029205 100644 --- a/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.h +++ b/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.m b/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.m index 2bbefacd69..2050fa98ec 100644 --- a/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.m +++ b/src/objective-c/RxLibrary/private/GRXNSFastEnumerator.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.h b/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.h index 5f4026e3a5..12aa51e213 100644 --- a/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.h +++ b/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.m b/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.m index 18f6ddfc26..f323ea14e6 100644 --- a/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.m +++ b/src/objective-c/RxLibrary/private/GRXNSScalarEnumerator.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/transformations/GRXMappingWriter.h b/src/objective-c/RxLibrary/transformations/GRXMappingWriter.h index 72249b486b..dcebb6132a 100644 --- a/src/objective-c/RxLibrary/transformations/GRXMappingWriter.h +++ b/src/objective-c/RxLibrary/transformations/GRXMappingWriter.h @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/objective-c/RxLibrary/transformations/GRXMappingWriter.m b/src/objective-c/RxLibrary/transformations/GRXMappingWriter.m index 8375aefdcd..8a41c819a6 100644 --- a/src/objective-c/RxLibrary/transformations/GRXMappingWriter.m +++ b/src/objective-c/RxLibrary/transformations/GRXMappingWriter.m @@ -1,6 +1,6 @@ /* * - * Copyright 2014, Google Inc. + * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/src/php/README.md b/src/php/README.md index 620c68fd7b..40c79e0dd4 100755 --- a/src/php/README.md +++ b/src/php/README.md @@ -1,4 +1,12 @@ -# PHP wrapper for the GRPC interfaces. + +#Overview + +This directory contains source code for PHP implementation of gRPC layered on shared C library. + +#Status + +Pre-Alpha : This gRPC PHP implementation is work-in-progress and is not expected to work yet. + ## LAYOUT diff --git a/src/python/README.md b/src/python/README.md new file mode 100755 index 0000000000..be2f2bedf9 --- /dev/null +++ b/src/python/README.md @@ -0,0 +1,34 @@ +GRPC Python +========= + +The Python facility of GRPC. + + +Prerequisites +----------------------- + +Python 2.7, virtualenv, pip, libprotobuf-dev, and libprotoc-dev. + + +Building from source +---------------------- + +- Build the GRPC core +E.g, from the root of the grpc [git repo](https://github.com/google/grpc) +``` +$ make shared_c static_c +``` + +- Use build_python.sh to build the Python code and install it into a virtual environment +``` +$ tools/run_tests/build_python.sh +``` + + +Testing +----------------------- + +- Use run_python.sh to run GRPC as it was installed into the virtual environment +``` +$ tools/run_tests/run_python.sh +``` diff --git a/src/python/interop/interop/methods.py b/src/python/interop/interop/methods.py index 854dbec8cc..26c1869f93 100644 --- a/src/python/interop/interop/methods.py +++ b/src/python/interop/interop/methods.py @@ -37,9 +37,11 @@ from interop import messages_pb2 def _empty_call(request): return empty_pb2.Empty() -EMPTY_CALL = utilities.unary_unary_rpc_method( - _empty_call, empty_pb2.Empty.SerializeToString, empty_pb2.Empty.FromString, +_CLIENT_EMPTY_CALL = utilities.unary_unary_client_rpc_method( empty_pb2.Empty.SerializeToString, empty_pb2.Empty.FromString) +_SERVER_EMPTY_CALL = utilities.unary_unary_server_rpc_method( + _empty_call, empty_pb2.Empty.FromString, + empty_pb2.Empty.SerializeToString) def _unary_call(request): @@ -48,11 +50,12 @@ def _unary_call(request): type=messages_pb2.COMPRESSABLE, body=b'\x00' * request.response_size)) -UNARY_CALL = utilities.unary_unary_rpc_method( - _unary_call, messages_pb2.SimpleRequest.SerializeToString, - messages_pb2.SimpleRequest.FromString, - messages_pb2.SimpleResponse.SerializeToString, +_CLIENT_UNARY_CALL = utilities.unary_unary_client_rpc_method( + messages_pb2.SimpleRequest.SerializeToString, messages_pb2.SimpleResponse.FromString) +_SERVER_UNARY_CALL = utilities.unary_unary_server_rpc_method( + _unary_call, messages_pb2.SimpleRequest.FromString, + messages_pb2.SimpleResponse.SerializeToString) def _streaming_output_call(request): @@ -62,12 +65,13 @@ def _streaming_output_call(request): type=request.response_type, body=b'\x00' * response_parameters.size)) -STREAMING_OUTPUT_CALL = utilities.unary_stream_rpc_method( - _streaming_output_call, +_CLIENT_STREAMING_OUTPUT_CALL = utilities.unary_stream_client_rpc_method( messages_pb2.StreamingOutputCallRequest.SerializeToString, - messages_pb2.StreamingOutputCallRequest.FromString, - messages_pb2.StreamingOutputCallResponse.SerializeToString, messages_pb2.StreamingOutputCallResponse.FromString) +_SERVER_STREAMING_OUTPUT_CALL = utilities.unary_stream_server_rpc_method( + _streaming_output_call, + messages_pb2.StreamingOutputCallRequest.FromString, + messages_pb2.StreamingOutputCallResponse.SerializeToString) def _streaming_input_call(request_iterator): @@ -78,12 +82,13 @@ def _streaming_input_call(request_iterator): return messages_pb2.StreamingInputCallResponse( aggregated_payload_size=aggregate_size) -STREAMING_INPUT_CALL = utilities.stream_unary_rpc_method( - _streaming_input_call, +_CLIENT_STREAMING_INPUT_CALL = utilities.stream_unary_client_rpc_method( messages_pb2.StreamingInputCallRequest.SerializeToString, - messages_pb2.StreamingInputCallRequest.FromString, - messages_pb2.StreamingInputCallResponse.SerializeToString, messages_pb2.StreamingInputCallResponse.FromString) +_SERVER_STREAMING_INPUT_CALL = utilities.stream_unary_server_rpc_method( + _streaming_input_call, + messages_pb2.StreamingInputCallRequest.FromString, + messages_pb2.StreamingInputCallResponse.SerializeToString) def _full_duplex_call(request_iterator): @@ -93,17 +98,47 @@ def _full_duplex_call(request_iterator): type=request.payload.type, body=b'\x00' * request.response_parameters[0].size)) -FULL_DUPLEX_CALL = utilities.stream_stream_rpc_method( - _full_duplex_call, +_CLIENT_FULL_DUPLEX_CALL = utilities.stream_stream_client_rpc_method( messages_pb2.StreamingOutputCallRequest.SerializeToString, - messages_pb2.StreamingOutputCallRequest.FromString, - messages_pb2.StreamingOutputCallResponse.SerializeToString, messages_pb2.StreamingOutputCallResponse.FromString) +_SERVER_FULL_DUPLEX_CALL = utilities.stream_stream_server_rpc_method( + _full_duplex_call, + messages_pb2.StreamingOutputCallRequest.FromString, + messages_pb2.StreamingOutputCallResponse.SerializeToString) # NOTE(nathaniel): Apparently this is the same as the full-duplex call? -HALF_DUPLEX_CALL = utilities.stream_stream_rpc_method( - _full_duplex_call, +_CLIENT_HALF_DUPLEX_CALL = utilities.stream_stream_client_rpc_method( messages_pb2.StreamingOutputCallRequest.SerializeToString, - messages_pb2.StreamingOutputCallRequest.FromString, - messages_pb2.StreamingOutputCallResponse.SerializeToString, messages_pb2.StreamingOutputCallResponse.FromString) +_SERVER_HALF_DUPLEX_CALL = utilities.stream_stream_server_rpc_method( + _full_duplex_call, + messages_pb2.StreamingOutputCallRequest.FromString, + messages_pb2.StreamingOutputCallResponse.SerializeToString) + + +_SERVICE_NAME = '/grpc.testing.TestService' + +EMPTY_CALL_METHOD_NAME = _SERVICE_NAME + '/EmptyCall' +UNARY_CALL_METHOD_NAME = _SERVICE_NAME + '/UnaryCall' +STREAMING_OUTPUT_CALL_METHOD_NAME = _SERVICE_NAME + '/StreamingOutputCall' +STREAMING_INPUT_CALL_METHOD_NAME = _SERVICE_NAME + '/StreamingInputCall' +FULL_DUPLEX_CALL_METHOD_NAME = _SERVICE_NAME + '/FullDuplexCall' +HALF_DUPLEX_CALL_METHOD_NAME = _SERVICE_NAME + '/HalfDuplexCall' + +CLIENT_METHODS = { + EMPTY_CALL_METHOD_NAME: _CLIENT_EMPTY_CALL, + UNARY_CALL_METHOD_NAME: _CLIENT_UNARY_CALL, + STREAMING_OUTPUT_CALL_METHOD_NAME: _CLIENT_STREAMING_OUTPUT_CALL, + STREAMING_INPUT_CALL_METHOD_NAME: _CLIENT_STREAMING_INPUT_CALL, + FULL_DUPLEX_CALL_METHOD_NAME: _CLIENT_FULL_DUPLEX_CALL, + HALF_DUPLEX_CALL_METHOD_NAME: _CLIENT_HALF_DUPLEX_CALL, +} + +SERVER_METHODS = { + EMPTY_CALL_METHOD_NAME: _SERVER_EMPTY_CALL, + UNARY_CALL_METHOD_NAME: _SERVER_UNARY_CALL, + STREAMING_OUTPUT_CALL_METHOD_NAME: _SERVER_STREAMING_OUTPUT_CALL, + STREAMING_INPUT_CALL_METHOD_NAME: _SERVER_STREAMING_INPUT_CALL, + FULL_DUPLEX_CALL_METHOD_NAME: _SERVER_FULL_DUPLEX_CALL, + HALF_DUPLEX_CALL_METHOD_NAME: _SERVER_HALF_DUPLEX_CALL, +} diff --git a/src/python/interop/interop/server.py b/src/python/interop/interop/server.py index 0035e062a4..785d482fe5 100644 --- a/src/python/interop/interop/server.py +++ b/src/python/interop/interop/server.py @@ -43,19 +43,6 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24 _PRIVATE_KEY_RESOURCE_PATH = 'credentials/server1.key' _CERTIFICATE_CHAIN_RESOURCE_PATH = 'credentials/server1.pem' -_METHODS = { - '/grpc.testing.TestService/EmptyCall': methods.EMPTY_CALL, - '/grpc.testing.TestService/UnaryCall': methods.UNARY_CALL, - '/grpc.testing.TestService/StreamingOutputCall': - methods.STREAMING_OUTPUT_CALL, - '/grpc.testing.TestService/StreamingInputCall': - methods.STREAMING_INPUT_CALL, - '/grpc.testing.TestService/FullDuplexCall': - methods.FULL_DUPLEX_CALL, - '/grpc.testing.TestService/HalfDuplexCall': - methods.HALF_DUPLEX_CALL, -} - def serve(): parser = argparse.ArgumentParser() @@ -72,10 +59,10 @@ def serve(): certificate_chain = pkg_resources.resource_string( __name__, _CERTIFICATE_CHAIN_RESOURCE_PATH) server = implementations.secure_server( - _METHODS, args.port, private_key, certificate_chain) + methods.SERVER_METHODS, args.port, private_key, certificate_chain) else: server = implementations.insecure_server( - _METHODS, args.port) + methods.SERVER_METHODS, args.port) server.start() logging.info('Server serving.') diff --git a/src/python/src/grpc/_adapter/_c.c b/src/python/src/grpc/_adapter/_c.c index 13eb93fe5a..55b9d0512c 100644 --- a/src/python/src/grpc/_adapter/_c.c +++ b/src/python/src/grpc/_adapter/_c.c @@ -40,19 +40,20 @@ #include "grpc/_adapter/_server.h" #include "grpc/_adapter/_server_credentials.h" -static PyObject *init(PyObject *self, PyObject *args) { +static PyObject *init(PyObject *self) { grpc_init(); Py_RETURN_NONE; } -static PyObject *shutdown(PyObject *self, PyObject *args) { +static PyObject *shutdown(PyObject *self) { grpc_shutdown(); Py_RETURN_NONE; } static PyMethodDef _c_methods[] = { - {"init", init, METH_VARARGS, "Initialize the module's static state."}, - {"shut_down", shutdown, METH_VARARGS, + {"init", (PyCFunction)init, METH_NOARGS, + "Initialize the module's static state."}, + {"shut_down", (PyCFunction)shutdown, METH_NOARGS, "Shut down the module's static state."}, {NULL}, }; diff --git a/src/python/src/grpc/_adapter/_call.c b/src/python/src/grpc/_adapter/_call.c index 7e62c1b7a3..325d3d5bbd 100644 --- a/src/python/src/grpc/_adapter/_call.c +++ b/src/python/src/grpc/_adapter/_call.c @@ -46,10 +46,11 @@ static int pygrpc_call_init(Call *self, PyObject *args, PyObject *kwds) { const char *method; const char *host; const double deadline; + static char *kwlist[] = {"channel", "method", "host", "deadline", NULL}; - if (!PyArg_ParseTuple(args, "O!ssd", &pygrpc_ChannelType, &channel, &method, - &host, &deadline)) { - self->c_call = NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!ssd:Call", kwlist, + &pygrpc_ChannelType, &channel, &method, + &host, &deadline)) { return -1; } @@ -77,7 +78,7 @@ static const PyObject *pygrpc_call_invoke(Call *self, PyObject *args) { grpc_call_error call_error; const PyObject *result; - if (!(PyArg_ParseTuple(args, "O!OO", &pygrpc_CompletionQueueType, + if (!(PyArg_ParseTuple(args, "O!OO:invoke", &pygrpc_CompletionQueueType, &completion_queue, &metadata_tag, &finish_tag))) { return NULL; } @@ -103,7 +104,7 @@ static const PyObject *pygrpc_call_write(Call *self, PyObject *args) { grpc_call_error call_error; const PyObject *result; - if (!(PyArg_ParseTuple(args, "s#O", &bytes, &length, &tag))) { + if (!(PyArg_ParseTuple(args, "s#O:write", &bytes, &length, &tag))) { return NULL; } @@ -123,15 +124,10 @@ static const PyObject *pygrpc_call_write(Call *self, PyObject *args) { return result; } -static const PyObject *pygrpc_call_complete(Call *self, PyObject *args) { - const PyObject *tag; +static const PyObject *pygrpc_call_complete(Call *self, PyObject *tag) { grpc_call_error call_error; const PyObject *result; - if (!(PyArg_ParseTuple(args, "O", &tag))) { - return NULL; - } - call_error = grpc_call_writes_done_old(self->c_call, (void *)tag); result = pygrpc_translate_call_error(call_error); @@ -147,7 +143,7 @@ static const PyObject *pygrpc_call_accept(Call *self, PyObject *args) { grpc_call_error call_error; const PyObject *result; - if (!(PyArg_ParseTuple(args, "O!O", &pygrpc_CompletionQueueType, + if (!(PyArg_ParseTuple(args, "O!O:accept", &pygrpc_CompletionQueueType, &completion_queue, &tag))) { return NULL; } @@ -164,21 +160,16 @@ static const PyObject *pygrpc_call_accept(Call *self, PyObject *args) { return result; } -static const PyObject *pygrpc_call_premetadata(Call *self, PyObject *args) { +static const PyObject *pygrpc_call_premetadata(Call *self) { /* TODO(b/18702680): Actually support metadata. */ return pygrpc_translate_call_error( grpc_call_server_end_initial_metadata_old(self->c_call, 0)); } -static const PyObject *pygrpc_call_read(Call *self, PyObject *args) { - const PyObject *tag; +static const PyObject *pygrpc_call_read(Call *self, PyObject *tag) { grpc_call_error call_error; const PyObject *result; - if (!(PyArg_ParseTuple(args, "O", &tag))) { - return NULL; - } - call_error = grpc_call_start_read_old(self->c_call, (void *)tag); result = pygrpc_translate_call_error(call_error); @@ -198,16 +189,30 @@ static const PyObject *pygrpc_call_status(Call *self, PyObject *args) { grpc_call_error call_error; const PyObject *result; - if (!(PyArg_ParseTuple(args, "OO", &status, &tag))) { + if (!(PyArg_ParseTuple(args, "OO:status", &status, &tag))) { return NULL; } code = PyObject_GetAttrString(status, "code"); + if (code == NULL) { + return NULL; + } details = PyObject_GetAttrString(status, "details"); + if (details == NULL) { + Py_DECREF(code); + return NULL; + } c_code = PyInt_AsLong(code); - c_message = PyBytes_AsString(details); Py_DECREF(code); + if (c_code == -1 && PyErr_Occurred()) { + Py_DECREF(details); + return NULL; + } + c_message = PyBytes_AsString(details); Py_DECREF(details); + if (c_message == NULL) { + return NULL; + } call_error = grpc_call_start_write_status_old(self->c_call, c_code, c_message, (void *)tag); @@ -228,12 +233,12 @@ static PyMethodDef methods[] = { "Invoke this call."}, {"write", (PyCFunction)pygrpc_call_write, METH_VARARGS, "Write bytes to this call."}, - {"complete", (PyCFunction)pygrpc_call_complete, METH_VARARGS, + {"complete", (PyCFunction)pygrpc_call_complete, METH_O, "Complete writes to this call."}, {"accept", (PyCFunction)pygrpc_call_accept, METH_VARARGS, "Accept an RPC."}, {"premetadata", (PyCFunction)pygrpc_call_premetadata, METH_VARARGS, "Indicate the end of leading metadata in the response."}, - {"read", (PyCFunction)pygrpc_call_read, METH_VARARGS, + {"read", (PyCFunction)pygrpc_call_read, METH_O, "Read bytes from this call."}, {"status", (PyCFunction)pygrpc_call_status, METH_VARARGS, "Report this call's status."}, @@ -242,7 +247,7 @@ static PyMethodDef methods[] = { {NULL}}; PyTypeObject pygrpc_CallType = { - PyObject_HEAD_INIT(NULL)0, /*ob_size*/ + PyVarObject_HEAD_INIT(NULL, 0) "_grpc.Call", /*tp_name*/ sizeof(Call), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -278,16 +283,16 @@ PyTypeObject pygrpc_CallType = { 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)pygrpc_call_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; int pygrpc_add_call(PyObject *module) { - pygrpc_CallType.tp_new = PyType_GenericNew; if (PyType_Ready(&pygrpc_CallType) < 0) { - PyErr_SetString(PyExc_RuntimeError, "Error defining pygrpc_CallType!"); return -1; } if (PyModule_AddObject(module, "Call", (PyObject *)&pygrpc_CallType) == -1) { - PyErr_SetString(PyExc_ImportError, "Couldn't add Call type to module!"); + return -1; } return 0; } diff --git a/src/python/src/grpc/_adapter/_channel.c b/src/python/src/grpc/_adapter/_channel.c index 6962722ed2..3ba943e4b2 100644 --- a/src/python/src/grpc/_adapter/_channel.c +++ b/src/python/src/grpc/_adapter/_channel.c @@ -38,9 +38,10 @@ static int pygrpc_channel_init(Channel *self, PyObject *args, PyObject *kwds) { const char *hostport; + static char *kwlist[] = {"hostport", NULL}; - if (!(PyArg_ParseTuple(args, "s", &hostport))) { - self->c_channel = NULL; + if (!(PyArg_ParseTupleAndKeywords(args, kwds, "s:Channel", kwlist, + &hostport))) { return -1; } @@ -56,7 +57,7 @@ static void pygrpc_channel_dealloc(Channel *self) { } PyTypeObject pygrpc_ChannelType = { - PyObject_HEAD_INIT(NULL)0, /*ob_size*/ + PyVarObject_HEAD_INIT(NULL, 0) "_grpc.Channel", /*tp_name*/ sizeof(Channel), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -92,17 +93,16 @@ PyTypeObject pygrpc_ChannelType = { 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)pygrpc_channel_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; int pygrpc_add_channel(PyObject *module) { - pygrpc_ChannelType.tp_new = PyType_GenericNew; if (PyType_Ready(&pygrpc_ChannelType) < 0) { - PyErr_SetString(PyExc_RuntimeError, "Error defining pygrpc_ChannelType!"); return -1; } if (PyModule_AddObject(module, "Channel", (PyObject *)&pygrpc_ChannelType) == -1) { - PyErr_SetString(PyExc_ImportError, "Couldn't add Channel type to module!"); return -1; } return 0; diff --git a/src/python/src/grpc/_adapter/_completion_queue.c b/src/python/src/grpc/_adapter/_completion_queue.c index 1d593d0d14..b56ca1926e 100644 --- a/src/python/src/grpc/_adapter/_completion_queue.c +++ b/src/python/src/grpc/_adapter/_completion_queue.c @@ -70,7 +70,7 @@ static PyObject *metadata_event_kind; static PyObject *finish_event_kind; static PyObject *pygrpc_as_py_time(gpr_timespec *timespec) { - return Py_BuildValue("f", + return PyFloat_FromDouble( timespec->tv_sec + ((double)timespec->tv_nsec) / 1.0E9); } @@ -116,67 +116,82 @@ static PyObject *pygrpc_status_code(grpc_status_code c_status_code) { } static PyObject *pygrpc_stop_event_args(grpc_event *c_event) { - return Py_BuildValue("(OOOOOOO)", stop_event_kind, Py_None, Py_None, Py_None, - Py_None, Py_None, Py_None); + return PyTuple_Pack(7, stop_event_kind, Py_None, Py_None, Py_None, + Py_None, Py_None, Py_None); } static PyObject *pygrpc_write_event_args(grpc_event *c_event) { PyObject *write_accepted = c_event->data.write_accepted == GRPC_OP_OK ? Py_True : Py_False; - return Py_BuildValue("(OOOOOOO)", write_event_kind, (PyObject *)c_event->tag, - write_accepted, Py_None, Py_None, Py_None, Py_None); + return PyTuple_Pack(7, write_event_kind, (PyObject *)c_event->tag, + write_accepted, Py_None, Py_None, Py_None, Py_None); } static PyObject *pygrpc_complete_event_args(grpc_event *c_event) { PyObject *complete_accepted = c_event->data.finish_accepted == GRPC_OP_OK ? Py_True : Py_False; - return Py_BuildValue("(OOOOOOO)", complete_event_kind, - (PyObject *)c_event->tag, Py_None, complete_accepted, - Py_None, Py_None, Py_None); + return PyTuple_Pack(7, complete_event_kind, (PyObject *)c_event->tag, + Py_None, complete_accepted, Py_None, Py_None, Py_None); } static PyObject *pygrpc_service_event_args(grpc_event *c_event) { if (c_event->data.server_rpc_new.method == NULL) { - return Py_BuildValue("(OOOOOOO)", service_event_kind, c_event->tag, - Py_None, Py_None, Py_None, Py_None, Py_None); + return PyTuple_Pack(7, service_event_kind, c_event->tag, + Py_None, Py_None, Py_None, Py_None, Py_None); } else { - PyObject *method = PyBytes_FromString(c_event->data.server_rpc_new.method); - PyObject *host = PyBytes_FromString(c_event->data.server_rpc_new.host); - PyObject *service_deadline = + PyObject *method = NULL; + PyObject *host = NULL; + PyObject *service_deadline = NULL; + Call *call = NULL; + PyObject *service_acceptance = NULL; + PyObject *event_args = NULL; + + method = PyBytes_FromString(c_event->data.server_rpc_new.method); + if (method == NULL) { + goto error; + } + host = PyBytes_FromString(c_event->data.server_rpc_new.host); + if (host == NULL) { + goto error; + } + service_deadline = pygrpc_as_py_time(&c_event->data.server_rpc_new.deadline); - - Call *call; - PyObject *service_acceptance_args; - PyObject *service_acceptance; - PyObject *event_args; + if (service_deadline == NULL) { + goto error; + } call = PyObject_New(Call, &pygrpc_CallType); + if (call == NULL) { + goto error; + } call->c_call = c_event->call; - service_acceptance_args = - Py_BuildValue("(OOOO)", call, method, host, service_deadline); - Py_DECREF(call); - Py_DECREF(method); - Py_DECREF(host); - Py_DECREF(service_deadline); - service_acceptance = - PyObject_CallObject(service_acceptance_class, service_acceptance_args); - Py_DECREF(service_acceptance_args); + PyObject_CallFunctionObjArgs(service_acceptance_class, call, method, + host, service_deadline, NULL); + if (service_acceptance == NULL) { + goto error; + } + + event_args = PyTuple_Pack(7, service_event_kind, + (PyObject *)c_event->tag, Py_None, Py_None, + service_acceptance, Py_None, Py_None); - event_args = Py_BuildValue("(OOOOOOO)", service_event_kind, - (PyObject *)c_event->tag, Py_None, Py_None, - service_acceptance, Py_None, Py_None); Py_DECREF(service_acceptance); +error: + Py_XDECREF(call); + Py_XDECREF(method); + Py_XDECREF(host); + Py_XDECREF(service_deadline); + return event_args; } } static PyObject *pygrpc_read_event_args(grpc_event *c_event) { if (c_event->data.read == NULL) { - return Py_BuildValue("(OOOOOOO)", read_event_kind, - (PyObject *)c_event->tag, Py_None, Py_None, Py_None, - Py_None, Py_None); + return PyTuple_Pack(7, read_event_kind, (PyObject *)c_event->tag, + Py_None, Py_None, Py_None, Py_None, Py_None); } else { size_t length; size_t offset; @@ -198,9 +213,11 @@ static PyObject *pygrpc_read_event_args(grpc_event *c_event) { grpc_byte_buffer_reader_destroy(reader); bytes = PyBytes_FromStringAndSize(c_bytes, length); gpr_free(c_bytes); - event_args = - Py_BuildValue("(OOOOOOO)", read_event_kind, (PyObject *)c_event->tag, - Py_None, Py_None, Py_None, bytes, Py_None); + if (bytes == NULL) { + return NULL; + } + event_args = PyTuple_Pack(7, read_event_kind, (PyObject *)c_event->tag, + Py_None, Py_None, Py_None, bytes, Py_None); Py_DECREF(bytes); return event_args; } @@ -208,15 +225,13 @@ static PyObject *pygrpc_read_event_args(grpc_event *c_event) { static PyObject *pygrpc_metadata_event_args(grpc_event *c_event) { /* TODO(nathaniel): Actual transmission of metadata. */ - return Py_BuildValue("(OOOOOOO)", metadata_event_kind, - (PyObject *)c_event->tag, Py_None, Py_None, Py_None, - Py_None, Py_None); + return PyTuple_Pack(7, metadata_event_kind, (PyObject *)c_event->tag, + Py_None, Py_None, Py_None, Py_None, Py_None); } static PyObject *pygrpc_finished_event_args(grpc_event *c_event) { PyObject *code; PyObject *details; - PyObject *status_args; PyObject *status; PyObject *event_args; @@ -230,19 +245,26 @@ static PyObject *pygrpc_finished_event_args(grpc_event *c_event) { } else { details = PyBytes_FromString(c_event->data.finished.details); } - status_args = Py_BuildValue("(OO)", code, details); + if (details == NULL) { + return NULL; + } + status = PyObject_CallFunctionObjArgs(status_class, code, details, NULL); Py_DECREF(details); - status = PyObject_CallObject(status_class, status_args); - Py_DECREF(status_args); - event_args = - Py_BuildValue("(OOOOOOO)", finish_event_kind, (PyObject *)c_event->tag, - Py_None, Py_None, Py_None, Py_None, status); + if (status == NULL) { + return NULL; + } + event_args = PyTuple_Pack(7, finish_event_kind, (PyObject *)c_event->tag, + Py_None, Py_None, Py_None, Py_None, status); Py_DECREF(status); return event_args; } static int pygrpc_completion_queue_init(CompletionQueue *self, PyObject *args, PyObject *kwds) { + static char *kwlist[] = {NULL}; + if (!PyArg_ParseTupleAndKeywords(args, kwds, ":CompletionQueue", kwlist)) { + return -1; + } self->c_completion_queue = grpc_completion_queue_create(); return 0; } @@ -262,7 +284,7 @@ static PyObject *pygrpc_completion_queue_get(CompletionQueue *self, PyObject *event_args; PyObject *event; - if (!(PyArg_ParseTuple(args, "O", &deadline))) { + if (!(PyArg_ParseTuple(args, "O:get", &deadline))) { return NULL; } @@ -270,6 +292,9 @@ static PyObject *pygrpc_completion_queue_get(CompletionQueue *self, deadline_timespec = gpr_inf_future; } else { double_deadline = PyFloat_AsDouble(deadline); + if (PyErr_Occurred()) { + return NULL; + } deadline_timespec = gpr_time_from_nanos((long)(double_deadline * 1.0E9)); } @@ -339,7 +364,7 @@ static PyMethodDef methods[] = { {NULL}}; PyTypeObject pygrpc_CompletionQueueType = { - PyObject_HEAD_INIT(NULL)0, /*ob_size*/ + PyVarObject_HEAD_INIT(NULL, 0) "_gprc.CompletionQueue", /*tp_name*/ sizeof(CompletionQueue), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -375,6 +400,8 @@ PyTypeObject pygrpc_CompletionQueueType = { 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)pygrpc_completion_queue_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; static int pygrpc_get_status_codes(PyObject *datatypes_module) { @@ -503,7 +530,6 @@ int pygrpc_add_completion_queue(PyObject *module) { char *datatypes_module_path = "grpc._adapter._datatypes"; PyObject *datatypes_module = PyImport_ImportModule(datatypes_module_path); if (datatypes_module == NULL) { - PyErr_SetString(PyExc_ImportError, datatypes_module_path); return -1; } status_class = PyObject_GetAttrString(datatypes_module, "Status"); @@ -512,29 +538,21 @@ int pygrpc_add_completion_queue(PyObject *module) { event_class = PyObject_GetAttrString(datatypes_module, "Event"); if (status_class == NULL || service_acceptance_class == NULL || event_class == NULL) { - PyErr_SetString(PyExc_ImportError, "Missing classes in _datatypes module!"); return -1; } if (pygrpc_get_status_codes(datatypes_module) == -1) { - PyErr_SetString(PyExc_ImportError, "Status codes import broken!"); return -1; } if (pygrpc_get_event_kinds(event_class) == -1) { - PyErr_SetString(PyExc_ImportError, "Event kinds import broken!"); return -1; } Py_DECREF(datatypes_module); - pygrpc_CompletionQueueType.tp_new = PyType_GenericNew; if (PyType_Ready(&pygrpc_CompletionQueueType) < 0) { - PyErr_SetString(PyExc_RuntimeError, - "Error defining pygrpc_CompletionQueueType!"); return -1; } if (PyModule_AddObject(module, "CompletionQueue", (PyObject *)&pygrpc_CompletionQueueType) == -1) { - PyErr_SetString(PyExc_ImportError, - "Couldn't add CompletionQueue type to module!"); return -1; } return 0; diff --git a/src/python/src/grpc/_adapter/_server.c b/src/python/src/grpc/_adapter/_server.c index d4bf5fb8f6..ae7ae5b5d2 100644 --- a/src/python/src/grpc/_adapter/_server.c +++ b/src/python/src/grpc/_adapter/_server.c @@ -43,9 +43,11 @@ static int pygrpc_server_init(Server *self, PyObject *args, PyObject *kwds) { const PyObject *completion_queue; PyObject *server_credentials; - if (!(PyArg_ParseTuple(args, "O!O", &pygrpc_CompletionQueueType, - &completion_queue, &server_credentials))) { - self->c_server = NULL; + static char *kwlist[] = {"completion_queue", "server_credentials", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O:Server", kwlist, + &pygrpc_CompletionQueueType, + &completion_queue, &server_credentials)) { return -1; } if (server_credentials == Py_None) { @@ -59,7 +61,9 @@ static int pygrpc_server_init(Server *self, PyObject *args, PyObject *kwds) { ((CompletionQueue *)completion_queue)->c_completion_queue, NULL); return 0; } else { - self->c_server = NULL; + PyErr_Format(PyExc_TypeError, + "server_credentials must be _grpc.ServerCredentials, not %s", + Py_TYPE(server_credentials)->tp_name); return -1; } } @@ -74,7 +78,9 @@ static void pygrpc_server_dealloc(Server *self) { static PyObject *pygrpc_server_add_http2_addr(Server *self, PyObject *args) { const char *addr; int port; - PyArg_ParseTuple(args, "s", &addr); + if (!PyArg_ParseTuple(args, "s:add_http2_addr", &addr)) { + return NULL; + } port = grpc_server_add_http2_port(self->c_server, addr); if (port == 0) { @@ -89,7 +95,9 @@ static PyObject *pygrpc_server_add_secure_http2_addr(Server *self, PyObject *args) { const char *addr; int port; - PyArg_ParseTuple(args, "s", &addr); + if (!PyArg_ParseTuple(args, "s:add_secure_http2_addr", &addr)) { + return NULL; + } port = grpc_server_add_secure_http2_port(self->c_server, addr); if (port == 0) { PyErr_SetString(PyExc_RuntimeError, "Couldn't add port to server!"); @@ -104,15 +112,10 @@ static PyObject *pygrpc_server_start(Server *self) { Py_RETURN_NONE; } -static const PyObject *pygrpc_server_service(Server *self, PyObject *args) { - const PyObject *tag; +static const PyObject *pygrpc_server_service(Server *self, PyObject *tag) { grpc_call_error call_error; const PyObject *result; - if (!(PyArg_ParseTuple(args, "O", &tag))) { - return NULL; - } - call_error = grpc_server_request_call_old(self->c_server, (void *)tag); result = pygrpc_translate_call_error(call_error); @@ -135,13 +138,13 @@ static PyMethodDef methods[] = { METH_VARARGS, "Add a secure HTTP2 address."}, {"start", (PyCFunction)pygrpc_server_start, METH_NOARGS, "Starts the server."}, - {"service", (PyCFunction)pygrpc_server_service, METH_VARARGS, + {"service", (PyCFunction)pygrpc_server_service, METH_O, "Services a call."}, {"stop", (PyCFunction)pygrpc_server_stop, METH_NOARGS, "Stops the server."}, {NULL}}; static PyTypeObject pygrpc_ServerType = { - PyObject_HEAD_INIT(NULL)0, /*ob_size*/ + PyVarObject_HEAD_INIT(NULL, 0) "_gprc.Server", /*tp_name*/ sizeof(Server), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -177,17 +180,16 @@ static PyTypeObject pygrpc_ServerType = { 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)pygrpc_server_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; int pygrpc_add_server(PyObject *module) { - pygrpc_ServerType.tp_new = PyType_GenericNew; if (PyType_Ready(&pygrpc_ServerType) < 0) { - PyErr_SetString(PyExc_RuntimeError, "Error defining pygrpc_ServerType!"); return -1; } if (PyModule_AddObject(module, "Server", (PyObject *)&pygrpc_ServerType) == -1) { - PyErr_SetString(PyExc_ImportError, "Couldn't add Server type to module!"); return -1; } return 0; diff --git a/src/python/src/grpc/_adapter/_server_credentials.c b/src/python/src/grpc/_adapter/_server_credentials.c index ae85fd3eb7..06e6b94974 100644 --- a/src/python/src/grpc/_adapter/_server_credentials.c +++ b/src/python/src/grpc/_adapter/_server_credentials.c @@ -47,21 +47,20 @@ static int pygrpc_server_credentials_init(ServerCredentials *self, PyObject *iterator; int i; PyObject *pair; + static char *kwlist[] = {"root_credentials", "pair_sequence", NULL}; - if (!(PyArg_ParseTuple(args, "zO", &root_certificates, &pair_sequence))) { - self->c_server_credentials = NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "zO:ServerCredentials", kwlist, + &root_certificates, &pair_sequence)) { return -1; } pair_count = PySequence_Length(pair_sequence); if (pair_count == -1) { - self->c_server_credentials = NULL; return -1; } iterator = PyObject_GetIter(pair_sequence); if (iterator == NULL) { - self->c_server_credentials = NULL; return -1; } pairs = gpr_malloc(pair_count * sizeof(grpc_ssl_pem_key_cert_pair)); @@ -72,8 +71,8 @@ static int pygrpc_server_credentials_init(ServerCredentials *self, error = 1; break; } - if (!(PyArg_ParseTuple(pair, "ss", &pairs[i].private_key, - &pairs[i].cert_chain))) { + if (!PyArg_ParseTuple(pair, "ss", &pairs[i].private_key, + &pairs[i].cert_chain)) { error = 1; Py_DECREF(pair); break; @@ -83,7 +82,6 @@ static int pygrpc_server_credentials_init(ServerCredentials *self, Py_DECREF(iterator); if (error) { - self->c_server_credentials = NULL; gpr_free(pairs); return -1; } else { @@ -102,7 +100,7 @@ static void pygrpc_server_credentials_dealloc(ServerCredentials *self) { } PyTypeObject pygrpc_ServerCredentialsType = { - PyObject_HEAD_INIT(NULL)0, /*ob_size*/ + PyVarObject_HEAD_INIT(NULL, 0) "_grpc.ServerCredencials", /*tp_name*/ sizeof(ServerCredentials), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -138,19 +136,16 @@ PyTypeObject pygrpc_ServerCredentialsType = { 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)pygrpc_server_credentials_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; int pygrpc_add_server_credentials(PyObject *module) { - pygrpc_ServerCredentialsType.tp_new = PyType_GenericNew; if (PyType_Ready(&pygrpc_ServerCredentialsType) < 0) { - PyErr_SetString(PyExc_RuntimeError, - "Error defining pygrpc_ServerCredentialsType!"); return -1; } if (PyModule_AddObject(module, "ServerCredentials", (PyObject *)&pygrpc_ServerCredentialsType) == -1) { - PyErr_SetString(PyExc_ImportError, - "Couldn't add ServerCredentials type to module!"); return -1; } return 0; diff --git a/src/python/src/grpc/early_adopter/_face_utilities.py b/src/python/src/grpc/early_adopter/_face_utilities.py index 714f2bb79c..3e37b08752 100644 --- a/src/python/src/grpc/early_adopter/_face_utilities.py +++ b/src/python/src/grpc/early_adopter/_face_utilities.py @@ -37,8 +37,8 @@ from grpc.early_adopter import interfaces class _InlineUnaryUnaryMethod(face_interfaces.InlineValueInValueOutMethod): - def __init__(self, unary_unary_rpc_method): - self._method = unary_unary_rpc_method + def __init__(self, unary_unary_server_rpc_method): + self._method = unary_unary_server_rpc_method def service(self, request, context): """See face_interfaces.InlineValueInValueOutMethod.service for spec.""" @@ -47,8 +47,8 @@ class _InlineUnaryUnaryMethod(face_interfaces.InlineValueInValueOutMethod): class _InlineUnaryStreamMethod(face_interfaces.InlineValueInStreamOutMethod): - def __init__(self, unary_stream_rpc_method): - self._method = unary_stream_rpc_method + def __init__(self, unary_stream_server_rpc_method): + self._method = unary_stream_server_rpc_method def service(self, request, context): """See face_interfaces.InlineValueInStreamOutMethod.service for spec.""" @@ -57,8 +57,8 @@ class _InlineUnaryStreamMethod(face_interfaces.InlineValueInStreamOutMethod): class _InlineStreamUnaryMethod(face_interfaces.InlineStreamInValueOutMethod): - def __init__(self, stream_unary_rpc_method): - self._method = stream_unary_rpc_method + def __init__(self, stream_unary_server_rpc_method): + self._method = stream_unary_server_rpc_method def service(self, request_iterator, context): """See face_interfaces.InlineStreamInValueOutMethod.service for spec.""" @@ -67,61 +67,99 @@ class _InlineStreamUnaryMethod(face_interfaces.InlineStreamInValueOutMethod): class _InlineStreamStreamMethod(face_interfaces.InlineStreamInStreamOutMethod): - def __init__(self, stream_stream_rpc_method): - self._method = stream_stream_rpc_method + def __init__(self, stream_stream_server_rpc_method): + self._method = stream_stream_server_rpc_method def service(self, request_iterator, context): """See face_interfaces.InlineStreamInStreamOutMethod.service for spec.""" return self._method.service_stream_stream(request_iterator) -class Breakdown(object): +class ClientBreakdown(object): + """An intermediate representation of invocation-side views of RPC methods. + + Attributes: + request_serializers: A dictionary from RPC method name to callable + behavior to be used serializing request values for the RPC. + response_deserializers: A dictionary from RPC method name to callable + behavior to be used deserializing response values for the RPC. + """ + __metaclass__ = abc.ABCMeta + + +class _EasyClientBreakdown( + ClientBreakdown, + collections.namedtuple( + '_EasyClientBreakdown', + ('request_serializers', 'response_deserializers'))): + pass + + +class ServerBreakdown(object): """An intermediate representation of implementations of RPC methods. Attributes: - unary_unary_methods: - unary_stream_methods: - stream_unary_methods: - stream_stream_methods: - request_serializers: - request_deserializers: - response_serializers: - response_deserializers: + unary_unary_methods: A dictionary from RPC method name to callable + behavior implementing the RPC method for unary-unary RPC methods. + unary_stream_methods: A dictionary from RPC method name to callable + behavior implementing the RPC method for unary-stream RPC methods. + stream_unary_methods: A dictionary from RPC method name to callable + behavior implementing the RPC method for stream-unary RPC methods. + stream_stream_methods: A dictionary from RPC method name to callable + behavior implementing the RPC method for stream-stream RPC methods. + request_deserializers: A dictionary from RPC method name to callable + behavior to be used deserializing request values for the RPC. + response_serializers: A dictionary from RPC method name to callable + behavior to be used serializing response values for the RPC. """ __metaclass__ = abc.ABCMeta -class _EasyBreakdown( - Breakdown, +class _EasyServerBreakdown( + ServerBreakdown, collections.namedtuple( - '_EasyBreakdown', - ['unary_unary_methods', 'unary_stream_methods', 'stream_unary_methods', - 'stream_stream_methods', 'request_serializers', - 'request_deserializers', 'response_serializers', - 'response_deserializers'])): + '_EasyServerBreakdown', + ('unary_unary_methods', 'unary_stream_methods', 'stream_unary_methods', + 'stream_stream_methods', 'request_deserializers', + 'response_serializers'))): pass -def break_down(methods): - """Breaks down RPC methods. +def client_break_down(methods): + """Derives a ClientBreakdown from several interfaces.ClientRpcMethods. + + Args: + methods: A dictionary from RPC mthod name to + interfaces.ClientRpcMethod object describing the RPCs. + + Returns: + A ClientBreakdown corresponding to the given methods. + """ + request_serializers = {} + response_deserializers = {} + for name, method in methods.iteritems(): + request_serializers[name] = method.serialize_request + response_deserializers[name] = method.deserialize_response + return _EasyClientBreakdown(request_serializers, response_deserializers) + + +def server_break_down(methods): + """Derives a ServerBreakdown from several interfaces.ServerRpcMethods. Args: methods: A dictionary from RPC mthod name to - interfaces.RpcMethod object describing the RPCs. + interfaces.ServerRpcMethod object describing the RPCs. Returns: - A Breakdown corresponding to the given methods. + A ServerBreakdown corresponding to the given methods. """ unary_unary = {} unary_stream = {} stream_unary = {} stream_stream = {} - request_serializers = {} request_deserializers = {} response_serializers = {} - response_deserializers = {} - for name, method in methods.iteritems(): cardinality = method.cardinality() if cardinality is interfaces.Cardinality.UNARY_UNARY: @@ -132,12 +170,9 @@ def break_down(methods): stream_unary[name] = _InlineStreamUnaryMethod(method) elif cardinality is interfaces.Cardinality.STREAM_STREAM: stream_stream[name] = _InlineStreamStreamMethod(method) - request_serializers[name] = method.serialize_request request_deserializers[name] = method.deserialize_request response_serializers[name] = method.serialize_response - response_deserializers[name] = method.deserialize_response - return _EasyBreakdown( + return _EasyServerBreakdown( unary_unary, unary_stream, stream_unary, stream_stream, - request_serializers, request_deserializers, response_serializers, - response_deserializers) + request_deserializers, response_serializers) diff --git a/src/python/src/grpc/early_adopter/implementations.py b/src/python/src/grpc/early_adopter/implementations.py index cd9dd5a57d..c549317d15 100644 --- a/src/python/src/grpc/early_adopter/implementations.py +++ b/src/python/src/grpc/early_adopter/implementations.py @@ -92,7 +92,7 @@ class _Server(interfaces.Server): def _build_server(methods, port, private_key, certificate_chain): - breakdown = _face_utilities.break_down(methods) + breakdown = _face_utilities.server_break_down(methods) return _Server(breakdown, port, private_key, certificate_chain) @@ -101,8 +101,8 @@ def insecure_server(methods, port): Args: methods: A dictionary from RPC method name to - interfaces.RpcMethod object describing the RPCs to be - serviced by the created server. + interfaces.ServerRpcMethod object describing the RPCs to + be serviced by the created server. port: The port on which to serve. Returns: @@ -117,8 +117,8 @@ def secure_server(methods, port, private_key, certificate_chain): Args: methods: A dictionary from RPC method name to - interfaces.RpcMethod object describing the RPCs to be - serviced by the created server. + interfaces.ServerRpcMethod object describing the RPCs to + be serviced by the created server. port: The port on which to serve. private_key: A pem-encoded private key. certificate_chain: A pem-encoded certificate chain. diff --git a/src/python/src/grpc/early_adopter/interfaces.py b/src/python/src/grpc/early_adopter/interfaces.py index 8d9a312133..0ec371f8e8 100644 --- a/src/python/src/grpc/early_adopter/interfaces.py +++ b/src/python/src/grpc/early_adopter/interfaces.py @@ -44,7 +44,7 @@ class Cardinality(enum.Enum): class RpcMethod(object): - """A sum type for the implementation of an RPC method.""" + """A type for the common aspects of RPC method specifications.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod @@ -59,6 +59,11 @@ class RpcMethod(object): """ raise NotImplementedError() + +class ClientRpcMethod(RpcMethod): + """Invocation-side description of an RPC method.""" + __metaclass__ = abc.ABCMeta + @abc.abstractmethod def serialize_request(self, request): """Serializes a request value. @@ -73,6 +78,25 @@ class RpcMethod(object): raise NotImplementedError() @abc.abstractmethod + def deserialize_response(self, serialized_response): + """Deserializes a response value. + + Args: + serialized_response: A bytestring that is the + serialization of a response value appropriate for this + RpcMethod. + + Returns: + A response value corresponding to the given bytestring. + """ + raise NotImplementedError() + + +class ServerRpcMethod(RpcMethod): + """Service-side description of an RPC method.""" + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod def deserialize_request(self, serialized_request): """Deserializes a request value. @@ -100,20 +124,6 @@ class RpcMethod(object): raise NotImplementedError() @abc.abstractmethod - def deserialize_response(self, serialized_response): - """Deserializes a response value. - - Args: - serialized_response: A bytestring that is the - serialization of a response value appropriate for this - RpcMethod. - - Returns: - A response value corresponding to the given bytestring. - """ - raise NotImplementedError() - - @abc.abstractmethod def service_unary_unary(self, request): """Carries out this RPC. @@ -182,7 +192,6 @@ class Server(object): """A GRPC Server.""" __metaclass__ = abc.ABCMeta - @abc.abstractmethod def start(self): """Instructs this server to commence service of RPCs.""" diff --git a/src/python/src/grpc/early_adopter/utilities.py b/src/python/src/grpc/early_adopter/utilities.py index a4ee253d83..9277d3f6ad 100644 --- a/src/python/src/grpc/early_adopter/utilities.py +++ b/src/python/src/grpc/early_adopter/utilities.py @@ -32,7 +32,7 @@ from grpc.early_adopter import interfaces -class _RpcMethod(interfaces.RpcMethod): +class _RpcMethod(interfaces.ClientRpcMethod, interfaces.ServerRpcMethod): def __init__( self, cardinality, unary_unary, unary_stream, stream_unary, @@ -85,129 +85,181 @@ class _RpcMethod(interfaces.RpcMethod): return self._stream_stream(request_iterator) -def unary_unary_rpc_method( - behavior, request_serializer, request_deserializer, response_serializer, - response_deserializer): - """Constructs an interfaces.RpcMethod for the given behavior. +def unary_unary_client_rpc_method(request_serializer, response_deserializer): + """Constructs an interfaces.ClientRpcMethod for a unary-unary RPC method. + + Args: + request_serializer: A callable that when called on a request + value returns a bytestring corresponding to that value. + response_deserializer: A callable that when called on a + bytestring returns the response value corresponding to + that bytestring. + + Returns: + An interfaces.ClientRpcMethod constructed from the given + arguments representing a unary-request/unary-response RPC + method. + """ + return _RpcMethod( + interfaces.Cardinality.UNARY_UNARY, None, None, None, None, + request_serializer, None, None, response_deserializer) + + +def unary_stream_client_rpc_method(request_serializer, response_deserializer): + """Constructs an interfaces.ClientRpcMethod for a unary-stream RPC method. + + Args: + request_serializer: A callable that when called on a request + value returns a bytestring corresponding to that value. + response_deserializer: A callable that when called on a + bytestring returns the response value corresponding to + that bytestring. + + Returns: + An interfaces.ClientRpcMethod constructed from the given + arguments representing a unary-request/streaming-response + RPC method. + """ + return _RpcMethod( + interfaces.Cardinality.UNARY_STREAM, None, None, None, None, + request_serializer, None, None, response_deserializer) + + +def stream_unary_client_rpc_method(request_serializer, response_deserializer): + """Constructs an interfaces.ClientRpcMethod for a stream-unary RPC method. + + Args: + request_serializer: A callable that when called on a request + value returns a bytestring corresponding to that value. + response_deserializer: A callable that when called on a + bytestring returns the response value corresponding to + that bytestring. + + Returns: + An interfaces.ClientRpcMethod constructed from the given + arguments representing a streaming-request/unary-response + RPC method. + """ + return _RpcMethod( + interfaces.Cardinality.STREAM_UNARY, None, None, None, None, + request_serializer, None, None, response_deserializer) + + +def stream_stream_client_rpc_method(request_serializer, response_deserializer): + """Constructs an interfaces.ClientRpcMethod for a stream-stream RPC method. + + Args: + request_serializer: A callable that when called on a request + value returns a bytestring corresponding to that value. + response_deserializer: A callable that when called on a + bytestring returns the response value corresponding to + that bytestring. + + Returns: + An interfaces.ClientRpcMethod constructed from the given + arguments representing a + streaming-request/streaming-response RPC method. + """ + return _RpcMethod( + interfaces.Cardinality.STREAM_STREAM, None, None, None, None, + request_serializer, None, None, response_deserializer) + + +def unary_unary_server_rpc_method( + behavior, request_deserializer, response_serializer): + """Constructs an interfaces.ServerRpcMethod for the given behavior. Args: behavior: A callable that implements a unary-unary RPC method that accepts a single request and returns a single response. - request_serializer: A callable that when called on a request - value returns a bytestring corresponding to that value. request_deserializer: A callable that when called on a bytestring returns the request value corresponding to that bytestring. response_serializer: A callable that when called on a response value returns the bytestring corresponding to that value. - response_deserializer: A callable that when called on a - bytestring returns the response value corresponding to - that bytestring. Returns: - An interfaces.RpcMethod constructed from the given + An interfaces.ServerRpcMethod constructed from the given arguments representing a unary-request/unary-response RPC method. """ return _RpcMethod( interfaces.Cardinality.UNARY_UNARY, behavior, None, None, None, - request_serializer, request_deserializer, response_serializer, - response_deserializer) + None, request_deserializer, response_serializer, None) -def unary_stream_rpc_method( - behavior, request_serializer, request_deserializer, response_serializer, - response_deserializer): - """Constructs an interfaces.RpcMethod for the given behavior. +def unary_stream_server_rpc_method( + behavior, request_deserializer, response_serializer): + """Constructs an interfaces.ServerRpcMethod for the given behavior. Args: behavior: A callable that implements a unary-stream RPC method that accepts a single request and returns an iterator of zero or more responses. - request_serializer: A callable that when called on a request - value returns a bytestring corresponding to that value. request_deserializer: A callable that when called on a bytestring returns the request value corresponding to that bytestring. response_serializer: A callable that when called on a response value returns the bytestring corresponding to that value. - response_deserializer: A callable that when called on a - bytestring returns the response value corresponding to - that bytestring. Returns: - An interfaces.RpcMethod constructed from the given + An interfaces.ServerRpcMethod constructed from the given arguments representing a unary-request/streaming-response RPC method. """ return _RpcMethod( interfaces.Cardinality.UNARY_STREAM, None, behavior, None, None, - request_serializer, request_deserializer, response_serializer, - response_deserializer) + None, request_deserializer, response_serializer, None) -def stream_unary_rpc_method( - behavior, request_serializer, request_deserializer, response_serializer, - response_deserializer): - """Constructs an interfaces.RpcMethod for the given behavior. +def stream_unary_server_rpc_method( + behavior, request_deserializer, response_serializer): + """Constructs an interfaces.ServerRpcMethod for the given behavior. Args: behavior: A callable that implements a stream-unary RPC method that accepts an iterator of zero or more requests and returns a single response. - request_serializer: A callable that when called on a request - value returns a bytestring corresponding to that value. request_deserializer: A callable that when called on a bytestring returns the request value corresponding to that bytestring. response_serializer: A callable that when called on a response value returns the bytestring corresponding to that value. - response_deserializer: A callable that when called on a - bytestring returns the response value corresponding to - that bytestring. Returns: - An interfaces.RpcMethod constructed from the given + An interfaces.ServerRpcMethod constructed from the given arguments representing a streaming-request/unary-response RPC method. """ return _RpcMethod( interfaces.Cardinality.STREAM_UNARY, None, None, behavior, None, - request_serializer, request_deserializer, response_serializer, - response_deserializer) + None, request_deserializer, response_serializer, None) -def stream_stream_rpc_method( - behavior, request_serializer, request_deserializer, response_serializer, - response_deserializer): - """Constructs an interfaces.RpcMethod for the given behavior. +def stream_stream_server_rpc_method( + behavior, request_deserializer, response_serializer): + """Constructs an interfaces.ServerRpcMethod for the given behavior. Args: behavior: A callable that implements a stream-stream RPC method that accepts an iterator of zero or more requests and returns an iterator of zero or more responses. - request_serializer: A callable that when called on a request - value returns a bytestring corresponding to that value. request_deserializer: A callable that when called on a bytestring returns the request value corresponding to that bytestring. response_serializer: A callable that when called on a response value returns the bytestring corresponding to that value. - response_deserializer: A callable that when called on a - bytestring returns the response value corresponding to - that bytestring. Returns: - An interfaces.RpcMethod constructed from the given + An interfaces.ServerRpcMethod constructed from the given arguments representing a streaming-request/streaming-response RPC method. """ return _RpcMethod( interfaces.Cardinality.STREAM_STREAM, None, None, None, behavior, - request_serializer, request_deserializer, response_serializer, - response_deserializer) + None, request_deserializer, response_serializer, None) diff --git a/src/python/src/grpc/framework/base/interfaces_test.py b/src/python/src/grpc/framework/base/interfaces_test_case.py index b86011c449..b86011c449 100644 --- a/src/python/src/grpc/framework/base/interfaces_test.py +++ b/src/python/src/grpc/framework/base/interfaces_test_case.py diff --git a/src/python/src/grpc/framework/base/packets/implementations_test.py b/src/python/src/grpc/framework/base/packets/implementations_test.py index 628f4b3909..e5855700c7 100644 --- a/src/python/src/grpc/framework/base/packets/implementations_test.py +++ b/src/python/src/grpc/framework/base/packets/implementations_test.py @@ -31,7 +31,7 @@ import unittest -from grpc.framework.base import interfaces_test +from grpc.framework.base import interfaces_test_case from grpc.framework.base import util from grpc.framework.base.packets import implementations from grpc.framework.foundation import logging_pool @@ -42,7 +42,7 @@ MAXIMUM_TIMEOUT = 60 class ImplementationsTest( - interfaces_test.FrontAndBackTest, unittest.TestCase): + interfaces_test_case.FrontAndBackTest, unittest.TestCase): def setUp(self): self.memory_transmission_pool = logging_pool.pool(POOL_MAX_WORKERS) @@ -53,7 +53,7 @@ class ImplementationsTest( self.back_transmission_pool = logging_pool.pool(POOL_MAX_WORKERS) self.back_utility_pool = logging_pool.pool(POOL_MAX_WORKERS) self.test_pool = logging_pool.pool(POOL_MAX_WORKERS) - self.test_servicer = interfaces_test.TestServicer(self.test_pool) + self.test_servicer = interfaces_test_case.TestServicer(self.test_pool) self.front = implementations.front( self.front_work_pool, self.front_transmission_pool, self.front_utility_pool) diff --git a/src/ruby/README.md b/src/ruby/README.md index 7ece7e2706..6e0e9db4a3 100755 --- a/src/ruby/README.md +++ b/src/ruby/README.md @@ -1,38 +1,43 @@ gRPC Ruby ========= -A Ruby implementation of gRPC, Google's RPC library. +A Ruby implementation of gRPC. +Status +------- + +Alpha : Ready for early adopters INSTALLATION PREREQUISITES -------------------------- -This requires Ruby 2.x, as the rpc api surface uses keyword args. +This requires Ruby 2.x, as the RPC API surface uses keyword args. -INSTALLING ----------- +QUICK - INSTALL +--------------- -- Install the gRPC core library - TODO: describe this, once the core distribution mechanism is defined. -``` -$ gem install grpc +- Clone this repository. +- Follow the instructions in [INSTALL](../../INSTALL) to install the gRPC C core. +- Use bundler to install +```sh +$ # from this directory +$ gem install bundler && bundle install ``` - Installing from source ---------------------- -- Build or Install the gRPC core -E.g, from the root of the grpc [git repo](https://github.com/google/grpc) -``` +- Build the gRPC C core +E.g, from the root of the gRPC [git repo](https://github.com/google/grpc) +```sh $ cd ../.. $ make && sudo make install ``` - Install Ruby 2.x. Consider doing this with [RVM](http://rvm.io), it's a nice way of controlling the exact ruby version that's used. -``` +```sh $ command curl -sSL https://rvm.io/mpapis.asc | gpg --import - $ \curl -sSL https://get.rvm.io | bash -s stable --ruby $ @@ -45,8 +50,8 @@ $ # and that the rvm command is installed $ gem install bundler ``` -- Finally, install grpc ruby locally. -``` +- Finally, install the gRPC gem locally. +```sh $ cd <install_dir> $ bundle install $ rake # compiles the extension, runs the unit tests, see rake -T for other options @@ -60,7 +65,7 @@ Directory structure is the layout for [ruby extensions](http://guides.rubygems.o - ext: the gRPC ruby extension - lib: - the entrypoint grpc ruby library to be used in a 'require' statement + the entrypoint gRPC ruby library to be used in a 'require' statement - spec: Rspec unittest - bin: @@ -69,6 +74,6 @@ Directory structure is the layout for [ruby extensions](http://guides.rubygems.o stub = Math::Math::Stub.new('my.test.math.server.com:8080') req = Math::DivArgs.new(dividend: 7, divisor: 3) logger.info("div(7/3): req=#{req.inspect}") -resp = stub.div(req, INFINITE_FUTURE) +resp = stub.div(req) logger.info("Answer: #{resp.inspect}") ``` diff --git a/src/ruby/bin/interop/interop_client.rb b/src/ruby/bin/interop/interop_client.rb index ef31f68f83..50a14e3a96 100755 --- a/src/ruby/bin/interop/interop_client.rb +++ b/src/ruby/bin/interop/interop_client.rb @@ -211,10 +211,8 @@ class NamedTests def compute_engine_creds resp = perform_large_unary(fill_username: true, fill_oauth_scope: true) - assert(@args.oauth_scope.include?(resp.oauth_scope), - 'service_account_creds: incorrect oauth_scope') assert_equal(@args.default_service_account, resp.username, - 'service_account_creds: incorrect username') + 'compute_engine_creds: incorrect username') p 'OK: compute_engine_creds' end diff --git a/src/ruby/grpc.gemspec b/src/ruby/grpc.gemspec index c479cc9616..bc59c234e5 100755 --- a/src/ruby/grpc.gemspec +++ b/src/ruby/grpc.gemspec @@ -5,12 +5,12 @@ require 'grpc/version' Gem::Specification.new do |s| s.name = 'grpc' - s.version = Google::RPC::VERSION + s.version = GRPC::VERSION s.authors = ['gRPC Authors'] - s.email = 'tbetbetbe@gmail.com' + s.email = 'temiola@google.com' s.homepage = 'https://github.com/google/grpc/tree/master/src/ruby' - s.summary = 'Google RPC system in Ruby' - s.description = 'Send RPCs from Ruby using Google\'s RPC system' + s.summary = 'GRPC system in Ruby' + s.description = 'Send RPCs from Ruby using GRPC' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- spec/*`.split("\n") |