diff --git a/.gitignore b/.gitignore index 45f8fdaa46f..8dc459ea276 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,7 @@ report.xml # port server log portlog.txt + +# gyp generated make files +*-gyp.mk +out \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 2d0c0097607..4d35fdece31 100644 --- a/.gitmodules +++ b/.gitmodules @@ -8,7 +8,7 @@ [submodule "third_party/protobuf"] path = third_party/protobuf url = https://github.com/google/protobuf.git - branch = v3.0.0-beta-1 + branch = v3.0.0-alpha-4.1 [submodule "third_party/gflags"] path = third_party/gflags url = https://github.com/gflags/gflags.git diff --git a/Makefile b/Makefile index 5a8ae1d1ac5..53faf408089 100644 --- a/Makefile +++ b/Makefile @@ -49,8 +49,11 @@ SYSTEM = MINGW32 endif +MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) ifndef BUILDDIR -BUILDDIR = . +BUILDDIR_ABSOLUTE = $(patsubst %/,%,$(dir $(MAKEFILE_PATH))) +else +BUILDDIR_ABSOLUTE = $(abspath $(BUILDDIR)) endif HAS_GCC = $(shell which gcc > /dev/null 2> /dev/null && echo true || echo false) @@ -76,10 +79,10 @@ endif endif -BINDIR = $(BUILDDIR)/bins -OBJDIR = $(BUILDDIR)/objs -LIBDIR = $(BUILDDIR)/libs -GENDIR = $(BUILDDIR)/gens +BINDIR = $(BUILDDIR_ABSOLUTE)/bins +OBJDIR = $(BUILDDIR_ABSOLUTE)/objs +LIBDIR = $(BUILDDIR_ABSOLUTE)/libs +GENDIR = $(BUILDDIR_ABSOLUTE)/gens # Configurations @@ -3371,8 +3374,6 @@ flaky_test_cxx: buildtests_cxx ifeq ($(HAS_ZOOKEEPER),true) test_zookeeper: buildtests_zookeeper - $(E) "[RUN] Testing zookeeper_test" - $(Q) $(BINDIR)/$(CONFIG)/zookeeper_test || ( echo test zookeeper_test failed ; exit 1 ) flaky_test_zookeeper: buildtests_zookeeper @@ -4199,13 +4200,13 @@ $(LIBDIR)/$(CONFIG)/libgrpc.a: $(ZLIB_DEP) $(OPENSSL_DEP) $(LIBGRPC_OBJS) $(Q) mkdir -p `dirname $@` $(Q) rm -f $(LIBDIR)/$(CONFIG)/libgrpc.a $(Q) $(AR) rcs $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBGRPC_OBJS) - $(Q) rm -rf tmp-merge-grpc - $(Q) mkdir tmp-merge-grpc - $(Q) ( cd tmp-merge-grpc ; $(AR) x ../$(LIBDIR)/$(CONFIG)/libgrpc.a ) - $(Q) for l in $(OPENSSL_MERGE_LIBS) ; do ( cd tmp-merge-grpc ; ar x ../$${l} ) ; done - $(Q) rm -f $(LIBDIR)/$(CONFIG)/libgrpc.a tmp-merge-grpc/__.SYMDEF* - $(Q) ar rcs $(LIBDIR)/$(CONFIG)/libgrpc.a tmp-merge-grpc/* - $(Q) rm -rf tmp-merge-grpc + $(Q) rm -rf $(BUILDDIR_ABSOLUTE)/tmp-merge-grpc + $(Q) mkdir $(BUILDDIR_ABSOLUTE)/tmp-merge-grpc + $(Q) ( cd $(BUILDDIR_ABSOLUTE)/tmp-merge-grpc ; $(AR) x $(LIBDIR)/$(CONFIG)/libgrpc.a ) + $(Q) for l in $(OPENSSL_MERGE_LIBS) ; do ( cd $(BUILDDIR_ABSOLUTE)/tmp-merge-grpc ; ar x $${l} ) ; done + $(Q) rm -f $(LIBDIR)/$(CONFIG)/libgrpc.a $(BUILDDIR_ABSOLUTE)/tmp-merge-grpc/__.SYMDEF* + $(Q) ar rcs $(LIBDIR)/$(CONFIG)/libgrpc.a $(BUILDDIR_ABSOLUTE)/tmp-merge-grpc/* + $(Q) rm -rf $(BUILDDIR_ABSOLUTE)/tmp-merge-grpc ifeq ($(SYSTEM),Darwin) $(Q) ranlib $(LIBDIR)/$(CONFIG)/libgrpc.a endif diff --git a/build.yaml b/build.yaml index 374ad382b44..4c6c6dc100e 100644 --- a/build.yaml +++ b/build.yaml @@ -1008,6 +1008,7 @@ targets: deps: [grpc++_test_util, grpc_test_util, grpc++, grpc, gpr_test_util, gpr] - name: zookeeper_test build: test + run: false language: c++ src: [test/cpp/end2end/zookeeper_test.cc] deps: [grpc++_test_util, grpc_test_util, grpc++, grpc_zookeeper, grpc, gpr_test_util, diff --git a/examples/csharp/route_guide/RouteGuide/RouteGuide.cs b/examples/csharp/route_guide/RouteGuide/RouteGuide.cs index 9bc6f307d26..deb97e1b2d7 100644 --- a/examples/csharp/route_guide/RouteGuide/RouteGuide.cs +++ b/examples/csharp/route_guide/RouteGuide/RouteGuide.cs @@ -7,7 +7,7 @@ using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; -namespace Examples { +namespace Routeguide { namespace Proto { @@ -23,29 +23,29 @@ namespace Examples { static RouteGuide() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( - "ChFyb3V0ZV9ndWlkZS5wcm90bxIIZXhhbXBsZXMiLAoFUG9pbnQSEAoIbGF0", - "aXR1ZGUYASABKAUSEQoJbG9uZ2l0dWRlGAIgASgFIkUKCVJlY3RhbmdsZRIb", - "CgJsbxgBIAEoCzIPLmV4YW1wbGVzLlBvaW50EhsKAmhpGAIgASgLMg8uZXhh", - "bXBsZXMuUG9pbnQiOgoHRmVhdHVyZRIMCgRuYW1lGAEgASgJEiEKCGxvY2F0", - "aW9uGAIgASgLMg8uZXhhbXBsZXMuUG9pbnQiPwoJUm91dGVOb3RlEiEKCGxv", - "Y2F0aW9uGAEgASgLMg8uZXhhbXBsZXMuUG9pbnQSDwoHbWVzc2FnZRgCIAEo", - "CSJiCgxSb3V0ZVN1bW1hcnkSEwoLcG9pbnRfY291bnQYASABKAUSFQoNZmVh", - "dHVyZV9jb3VudBgCIAEoBRIQCghkaXN0YW5jZRgDIAEoBRIUCgxlbGFwc2Vk", - "X3RpbWUYBCABKAUy9QEKClJvdXRlR3VpZGUSMgoKR2V0RmVhdHVyZRIPLmV4", - "YW1wbGVzLlBvaW50GhEuZXhhbXBsZXMuRmVhdHVyZSIAEjoKDExpc3RGZWF0", - "dXJlcxITLmV4YW1wbGVzLlJlY3RhbmdsZRoRLmV4YW1wbGVzLkZlYXR1cmUi", - "ADABEjoKC1JlY29yZFJvdXRlEg8uZXhhbXBsZXMuUG9pbnQaFi5leGFtcGxl", - "cy5Sb3V0ZVN1bW1hcnkiACgBEjsKCVJvdXRlQ2hhdBITLmV4YW1wbGVzLlJv", - "dXRlTm90ZRoTLmV4YW1wbGVzLlJvdXRlTm90ZSIAKAEwAUIPCgdleC5ncnBj", - "ogIDUlRHYgZwcm90bzM=")); + "ChFyb3V0ZV9ndWlkZS5wcm90bxIKcm91dGVndWlkZSIsCgVQb2ludBIQCghs", + "YXRpdHVkZRgBIAEoBRIRCglsb25naXR1ZGUYAiABKAUiSQoJUmVjdGFuZ2xl", + "Eh0KAmxvGAEgASgLMhEucm91dGVndWlkZS5Qb2ludBIdCgJoaRgCIAEoCzIR", + "LnJvdXRlZ3VpZGUuUG9pbnQiPAoHRmVhdHVyZRIMCgRuYW1lGAEgASgJEiMK", + "CGxvY2F0aW9uGAIgASgLMhEucm91dGVndWlkZS5Qb2ludCJBCglSb3V0ZU5v", + "dGUSIwoIbG9jYXRpb24YASABKAsyES5yb3V0ZWd1aWRlLlBvaW50Eg8KB21l", + "c3NhZ2UYAiABKAkiYgoMUm91dGVTdW1tYXJ5EhMKC3BvaW50X2NvdW50GAEg", + "ASgFEhUKDWZlYXR1cmVfY291bnQYAiABKAUSEAoIZGlzdGFuY2UYAyABKAUS", + "FAoMZWxhcHNlZF90aW1lGAQgASgFMoUCCgpSb3V0ZUd1aWRlEjYKCkdldEZl", + "YXR1cmUSES5yb3V0ZWd1aWRlLlBvaW50GhMucm91dGVndWlkZS5GZWF0dXJl", + "IgASPgoMTGlzdEZlYXR1cmVzEhUucm91dGVndWlkZS5SZWN0YW5nbGUaEy5y", + "b3V0ZWd1aWRlLkZlYXR1cmUiADABEj4KC1JlY29yZFJvdXRlEhEucm91dGVn", + "dWlkZS5Qb2ludBoYLnJvdXRlZ3VpZGUuUm91dGVTdW1tYXJ5IgAoARI/CglS", + "b3V0ZUNoYXQSFS5yb3V0ZWd1aWRlLlJvdXRlTm90ZRoVLnJvdXRlZ3VpZGUu", + "Um91dGVOb3RlIgAoATABQg8KB2V4LmdycGOiAgNSVEdiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { - new pbr::GeneratedCodeInfo(typeof(global::Examples.Point), new[]{ "Latitude", "Longitude" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Examples.Rectangle), new[]{ "Lo", "Hi" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Examples.Feature), new[]{ "Name", "Location" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Examples.RouteNote), new[]{ "Location", "Message" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Examples.RouteSummary), new[]{ "PointCount", "FeatureCount", "Distance", "ElapsedTime" }, null, null, null) + new pbr::GeneratedCodeInfo(typeof(global::Routeguide.Point), new[]{ "Latitude", "Longitude" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Routeguide.Rectangle), new[]{ "Lo", "Hi" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Routeguide.Feature), new[]{ "Name", "Location" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Routeguide.RouteNote), new[]{ "Location", "Message" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Routeguide.RouteSummary), new[]{ "PointCount", "FeatureCount", "Distance", "ElapsedTime" }, null, null, null) })); } #endregion @@ -59,7 +59,7 @@ namespace Examples { public static pb::MessageParser Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Examples.Proto.RouteGuide.Descriptor.MessageTypes[0]; } + get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -187,7 +187,7 @@ namespace Examples { public static pb::MessageParser Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Examples.Proto.RouteGuide.Descriptor.MessageTypes[1]; } + get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -210,8 +210,8 @@ namespace Examples { } public const int LoFieldNumber = 1; - private global::Examples.Point lo_; - public global::Examples.Point Lo { + private global::Routeguide.Point lo_; + public global::Routeguide.Point Lo { get { return lo_; } set { lo_ = value; @@ -219,8 +219,8 @@ namespace Examples { } public const int HiFieldNumber = 2; - private global::Examples.Point hi_; - public global::Examples.Point Hi { + private global::Routeguide.Point hi_; + public global::Routeguide.Point Hi { get { return hi_; } set { hi_ = value; @@ -282,13 +282,13 @@ namespace Examples { } if (other.lo_ != null) { if (lo_ == null) { - lo_ = new global::Examples.Point(); + lo_ = new global::Routeguide.Point(); } Lo.MergeFrom(other.Lo); } if (other.hi_ != null) { if (hi_ == null) { - hi_ = new global::Examples.Point(); + hi_ = new global::Routeguide.Point(); } Hi.MergeFrom(other.Hi); } @@ -303,14 +303,14 @@ namespace Examples { break; case 10: { if (lo_ == null) { - lo_ = new global::Examples.Point(); + lo_ = new global::Routeguide.Point(); } input.ReadMessage(lo_); break; } case 18: { if (hi_ == null) { - hi_ = new global::Examples.Point(); + hi_ = new global::Routeguide.Point(); } input.ReadMessage(hi_); break; @@ -327,7 +327,7 @@ namespace Examples { public static pb::MessageParser Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Examples.Proto.RouteGuide.Descriptor.MessageTypes[2]; } + get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -359,8 +359,8 @@ namespace Examples { } public const int LocationFieldNumber = 2; - private global::Examples.Point location_; - public global::Examples.Point Location { + private global::Routeguide.Point location_; + public global::Routeguide.Point Location { get { return location_; } set { location_ = value; @@ -425,7 +425,7 @@ namespace Examples { } if (other.location_ != null) { if (location_ == null) { - location_ = new global::Examples.Point(); + location_ = new global::Routeguide.Point(); } Location.MergeFrom(other.Location); } @@ -444,7 +444,7 @@ namespace Examples { } case 18: { if (location_ == null) { - location_ = new global::Examples.Point(); + location_ = new global::Routeguide.Point(); } input.ReadMessage(location_); break; @@ -461,7 +461,7 @@ namespace Examples { public static pb::MessageParser Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Examples.Proto.RouteGuide.Descriptor.MessageTypes[3]; } + get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -484,8 +484,8 @@ namespace Examples { } public const int LocationFieldNumber = 1; - private global::Examples.Point location_; - public global::Examples.Point Location { + private global::Routeguide.Point location_; + public global::Routeguide.Point Location { get { return location_; } set { location_ = value; @@ -556,7 +556,7 @@ namespace Examples { } if (other.location_ != null) { if (location_ == null) { - location_ = new global::Examples.Point(); + location_ = new global::Routeguide.Point(); } Location.MergeFrom(other.Location); } @@ -574,7 +574,7 @@ namespace Examples { break; case 10: { if (location_ == null) { - location_ = new global::Examples.Point(); + location_ = new global::Routeguide.Point(); } input.ReadMessage(location_); break; @@ -595,7 +595,7 @@ namespace Examples { public static pb::MessageParser Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Examples.Proto.RouteGuide.Descriptor.MessageTypes[4]; } + get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { diff --git a/examples/csharp/route_guide/RouteGuide/RouteGuideGrpc.cs b/examples/csharp/route_guide/RouteGuide/RouteGuideGrpc.cs index f2dc1c2ec09..d60256fff65 100644 --- a/examples/csharp/route_guide/RouteGuide/RouteGuideGrpc.cs +++ b/examples/csharp/route_guide/RouteGuide/RouteGuideGrpc.cs @@ -7,39 +7,39 @@ using System.Threading; using System.Threading.Tasks; using Grpc.Core; -namespace Examples { +namespace Routeguide { public static class RouteGuide { - static readonly string __ServiceName = "examples.RouteGuide"; + static readonly string __ServiceName = "routeguide.RouteGuide"; - static readonly Marshaller __Marshaller_Point = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Examples.Point.Parser.ParseFrom); - static readonly Marshaller __Marshaller_Feature = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Examples.Feature.Parser.ParseFrom); - static readonly Marshaller __Marshaller_Rectangle = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Examples.Rectangle.Parser.ParseFrom); - static readonly Marshaller __Marshaller_RouteSummary = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Examples.RouteSummary.Parser.ParseFrom); - static readonly Marshaller __Marshaller_RouteNote = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Examples.RouteNote.Parser.ParseFrom); + static readonly Marshaller __Marshaller_Point = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Point.Parser.ParseFrom); + static readonly Marshaller __Marshaller_Feature = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Feature.Parser.ParseFrom); + static readonly Marshaller __Marshaller_Rectangle = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Rectangle.Parser.ParseFrom); + static readonly Marshaller __Marshaller_RouteSummary = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.RouteSummary.Parser.ParseFrom); + static readonly Marshaller __Marshaller_RouteNote = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.RouteNote.Parser.ParseFrom); - static readonly Method __Method_GetFeature = new Method( + static readonly Method __Method_GetFeature = new Method( MethodType.Unary, __ServiceName, "GetFeature", __Marshaller_Point, __Marshaller_Feature); - static readonly Method __Method_ListFeatures = new Method( + static readonly Method __Method_ListFeatures = new Method( MethodType.ServerStreaming, __ServiceName, "ListFeatures", __Marshaller_Rectangle, __Marshaller_Feature); - static readonly Method __Method_RecordRoute = new Method( + static readonly Method __Method_RecordRoute = new Method( MethodType.ClientStreaming, __ServiceName, "RecordRoute", __Marshaller_Point, __Marshaller_RouteSummary); - static readonly Method __Method_RouteChat = new Method( + static readonly Method __Method_RouteChat = new Method( MethodType.DuplexStreaming, __ServiceName, "RouteChat", @@ -49,31 +49,31 @@ namespace Examples { // service descriptor public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { - get { return global::Examples.Proto.RouteGuide.Descriptor.Services[0]; } + get { return global::Routeguide.Proto.RouteGuide.Descriptor.Services[0]; } } // client interface public interface IRouteGuideClient { - global::Examples.Feature GetFeature(global::Examples.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); - global::Examples.Feature GetFeature(global::Examples.Point request, CallOptions options); - AsyncUnaryCall GetFeatureAsync(global::Examples.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); - AsyncUnaryCall GetFeatureAsync(global::Examples.Point request, CallOptions options); - AsyncServerStreamingCall ListFeatures(global::Examples.Rectangle request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); - AsyncServerStreamingCall ListFeatures(global::Examples.Rectangle request, CallOptions options); - AsyncClientStreamingCall RecordRoute(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); - AsyncClientStreamingCall RecordRoute(CallOptions options); - AsyncDuplexStreamingCall RouteChat(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); - AsyncDuplexStreamingCall RouteChat(CallOptions options); + global::Routeguide.Feature GetFeature(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); + global::Routeguide.Feature GetFeature(global::Routeguide.Point request, CallOptions options); + AsyncUnaryCall GetFeatureAsync(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); + AsyncUnaryCall GetFeatureAsync(global::Routeguide.Point request, CallOptions options); + AsyncServerStreamingCall ListFeatures(global::Routeguide.Rectangle request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); + AsyncServerStreamingCall ListFeatures(global::Routeguide.Rectangle request, CallOptions options); + AsyncClientStreamingCall RecordRoute(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); + AsyncClientStreamingCall RecordRoute(CallOptions options); + AsyncDuplexStreamingCall RouteChat(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); + AsyncDuplexStreamingCall RouteChat(CallOptions options); } // server-side interface public interface IRouteGuide { - Task GetFeature(global::Examples.Point request, ServerCallContext context); - Task ListFeatures(global::Examples.Rectangle request, IServerStreamWriter responseStream, ServerCallContext context); - Task RecordRoute(IAsyncStreamReader requestStream, ServerCallContext context); - Task RouteChat(IAsyncStreamReader requestStream, IServerStreamWriter responseStream, ServerCallContext context); + Task GetFeature(global::Routeguide.Point request, ServerCallContext context); + Task ListFeatures(global::Routeguide.Rectangle request, IServerStreamWriter responseStream, ServerCallContext context); + Task RecordRoute(IAsyncStreamReader requestStream, ServerCallContext context); + Task RouteChat(IAsyncStreamReader requestStream, IServerStreamWriter responseStream, ServerCallContext context); } // client stub @@ -82,52 +82,52 @@ namespace Examples { public RouteGuideClient(Channel channel) : base(channel) { } - public global::Examples.Feature GetFeature(global::Examples.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + public global::Routeguide.Feature GetFeature(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_GetFeature, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } - public global::Examples.Feature GetFeature(global::Examples.Point request, CallOptions options) + public global::Routeguide.Feature GetFeature(global::Routeguide.Point request, CallOptions options) { var call = CreateCall(__Method_GetFeature, options); return Calls.BlockingUnaryCall(call, request); } - public AsyncUnaryCall GetFeatureAsync(global::Examples.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + public AsyncUnaryCall GetFeatureAsync(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_GetFeature, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } - public AsyncUnaryCall GetFeatureAsync(global::Examples.Point request, CallOptions options) + public AsyncUnaryCall GetFeatureAsync(global::Routeguide.Point request, CallOptions options) { var call = CreateCall(__Method_GetFeature, options); return Calls.AsyncUnaryCall(call, request); } - public AsyncServerStreamingCall ListFeatures(global::Examples.Rectangle request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + public AsyncServerStreamingCall ListFeatures(global::Routeguide.Rectangle request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_ListFeatures, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncServerStreamingCall(call, request); } - public AsyncServerStreamingCall ListFeatures(global::Examples.Rectangle request, CallOptions options) + public AsyncServerStreamingCall ListFeatures(global::Routeguide.Rectangle request, CallOptions options) { var call = CreateCall(__Method_ListFeatures, options); return Calls.AsyncServerStreamingCall(call, request); } - public AsyncClientStreamingCall RecordRoute(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + public AsyncClientStreamingCall RecordRoute(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_RecordRoute, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncClientStreamingCall(call); } - public AsyncClientStreamingCall RecordRoute(CallOptions options) + public AsyncClientStreamingCall RecordRoute(CallOptions options) { var call = CreateCall(__Method_RecordRoute, options); return Calls.AsyncClientStreamingCall(call); } - public AsyncDuplexStreamingCall RouteChat(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + public AsyncDuplexStreamingCall RouteChat(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_RouteChat, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); } - public AsyncDuplexStreamingCall RouteChat(CallOptions options) + public AsyncDuplexStreamingCall RouteChat(CallOptions options) { var call = CreateCall(__Method_RouteChat, options); return Calls.AsyncDuplexStreamingCall(call); diff --git a/examples/csharp/route_guide/RouteGuide/RouteGuideUtil.cs b/examples/csharp/route_guide/RouteGuide/RouteGuideUtil.cs index 21a0be43d21..e898738c7ae 100644 --- a/examples/csharp/route_guide/RouteGuide/RouteGuideUtil.cs +++ b/examples/csharp/route_guide/RouteGuide/RouteGuideUtil.cs @@ -7,7 +7,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Examples +namespace Routeguide { /// /// Utility methods for the route guide example. diff --git a/examples/csharp/route_guide/RouteGuideClient/Program.cs b/examples/csharp/route_guide/RouteGuideClient/Program.cs index 4ddb526585f..be65fc38cd4 100644 --- a/examples/csharp/route_guide/RouteGuideClient/Program.cs +++ b/examples/csharp/route_guide/RouteGuideClient/Program.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Examples +namespace Routeguide { class Program { diff --git a/examples/csharp/route_guide/RouteGuideServer/Program.cs b/examples/csharp/route_guide/RouteGuideServer/Program.cs index 0a4d73f391d..baced0b10ab 100644 --- a/examples/csharp/route_guide/RouteGuideServer/Program.cs +++ b/examples/csharp/route_guide/RouteGuideServer/Program.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Examples +namespace Routeguide { class Program { diff --git a/examples/csharp/route_guide/RouteGuideServer/RouteGuideImpl.cs b/examples/csharp/route_guide/RouteGuideServer/RouteGuideImpl.cs index fbe0f4471cf..b82829438d6 100644 --- a/examples/csharp/route_guide/RouteGuideServer/RouteGuideImpl.cs +++ b/examples/csharp/route_guide/RouteGuideServer/RouteGuideImpl.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Grpc.Core.Utils; -namespace Examples +namespace Routeguide { /// /// Example implementation of RouteGuide server. diff --git a/src/core/iomgr/tcp_windows.c b/src/core/iomgr/tcp_windows.c index 9cae07316a9..b67683dbfd9 100644 --- a/src/core/iomgr/tcp_windows.c +++ b/src/core/iomgr/tcp_windows.c @@ -149,7 +149,7 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *tcpp, int success) { int do_abort = 0; if (success) { - if (socket->read_info.wsa_error != 0) { + if (socket->read_info.wsa_error != 0 && !tcp->shutting_down) { if (socket->read_info.wsa_error != WSAECONNRESET) { char *utf8_message = gpr_format_message(info->wsa_error); gpr_log(GPR_ERROR, "ReadFile overlapped error: %s", utf8_message); @@ -158,7 +158,7 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *tcpp, int success) { success = 0; gpr_slice_unref(tcp->read_slice); } else { - if (info->bytes_transfered != 0) { + if (info->bytes_transfered != 0 && !tcp->shutting_down) { sub = gpr_slice_sub_no_ref(tcp->read_slice, 0, info->bytes_transfered); gpr_slice_buffer_add(tcp->read_slices, sub); success = 1; diff --git a/src/core/security/client_auth_filter.c b/src/core/security/client_auth_filter.c index e24281bdff2..c152a06498d 100644 --- a/src/core/security/client_auth_filter.c +++ b/src/core/security/client_auth_filter.c @@ -212,7 +212,8 @@ static void auth_start_transport_op(grpc_exec_ctx *exec_ctx, size_t i; grpc_client_security_context *sec_ctx = NULL; - if (calld->security_context_set == 0) { + if (calld->security_context_set == 0 && + op->cancel_with_status == GRPC_STATUS_OK) { calld->security_context_set = 1; GPR_ASSERT(op->context); if (op->context[GRPC_CONTEXT_SECURITY].value == NULL) { @@ -227,11 +228,11 @@ static void auth_start_transport_op(grpc_exec_ctx *exec_ctx, chand->security_connector->base.auth_context, "client_auth_filter"); } - if (op->bind_pollset) { + if (op->bind_pollset != NULL) { calld->pollset = op->bind_pollset; } - if (op->send_ops && !calld->sent_initial_metadata) { + if (op->send_ops != NULL && !calld->sent_initial_metadata) { size_t nops = op->send_ops->nops; grpc_stream_op *ops = op->send_ops->ops; for (i = 0; i < nops; i++) { diff --git a/src/csharp/Grpc.Core/Logging/ConsoleLogger.cs b/src/csharp/Grpc.Core/Logging/ConsoleLogger.cs index 35561d25d8a..5c5b8021641 100644 --- a/src/csharp/Grpc.Core/Logging/ConsoleLogger.cs +++ b/src/csharp/Grpc.Core/Logging/ConsoleLogger.cs @@ -79,48 +79,72 @@ namespace Grpc.Core.Logging } /// Logs a message with severity Debug. - public void Debug(string message, params object[] formatArgs) + public void Debug(string message) { - Log("D", message, formatArgs); + Log("D", message); + } + + /// Logs a formatted message with severity Debug. + public void Debug(string format, params object[] formatArgs) + { + Debug(string.Format(format, formatArgs)); } /// Logs a message with severity Info. - public void Info(string message, params object[] formatArgs) + public void Info(string message) + { + Log("I", message); + } + + /// Logs a formatted message with severity Info. + public void Info(string format, params object[] formatArgs) { - Log("I", message, formatArgs); + Info(string.Format(format, formatArgs)); } /// Logs a message with severity Warning. - public void Warning(string message, params object[] formatArgs) + public void Warning(string message) { - Log("W", message, formatArgs); + Log("W", message); + } + + /// Logs a formatted message with severity Warning. + public void Warning(string format, params object[] formatArgs) + { + Warning(string.Format(format, formatArgs)); } /// Logs a message and an associated exception with severity Warning. - public void Warning(Exception exception, string message, params object[] formatArgs) + public void Warning(Exception exception, string message) { - Log("W", message + " " + exception, formatArgs); + Warning(message + " " + exception); } /// Logs a message with severity Error. - public void Error(string message, params object[] formatArgs) + public void Error(string message) + { + Log("E", message); + } + + /// Logs a formatted message with severity Error. + public void Error(string format, params object[] formatArgs) { - Log("E", message, formatArgs); + Error(string.Format(format, formatArgs)); } /// Logs a message and an associated exception with severity Error. - public void Error(Exception exception, string message, params object[] formatArgs) + public void Error(Exception exception, string message) { - Log("E", message + " " + exception, formatArgs); + Error(message + " " + exception); } - private void Log(string severityString, string message, object[] formatArgs) + private void Log(string severityString, string message) { Console.Error.WriteLine("{0}{1} {2}{3}", severityString, DateTime.Now, forTypeString, - string.Format(message, formatArgs)); + message); } } } diff --git a/src/csharp/Grpc.Core/Logging/ILogger.cs b/src/csharp/Grpc.Core/Logging/ILogger.cs index 61e0c91388b..7c0326422f4 100644 --- a/src/csharp/Grpc.Core/Logging/ILogger.cs +++ b/src/csharp/Grpc.Core/Logging/ILogger.cs @@ -43,21 +43,33 @@ namespace Grpc.Core.Logging ILogger ForType(); /// Logs a message with severity Debug. - void Debug(string message, params object[] formatArgs); + void Debug(string message); + + /// Logs a formatted message with severity Debug. + void Debug(string format, params object[] formatArgs); /// Logs a message with severity Info. - void Info(string message, params object[] formatArgs); + void Info(string message); + + /// Logs a formatted message with severity Info. + void Info(string format, params object[] formatArgs); /// Logs a message with severity Warning. - void Warning(string message, params object[] formatArgs); + void Warning(string message); + + /// Logs a formatted message with severity Warning. + void Warning(string format, params object[] formatArgs); /// Logs a message and an associated exception with severity Warning. - void Warning(Exception exception, string message, params object[] formatArgs); + void Warning(Exception exception, string message); /// Logs a message with severity Error. - void Error(string message, params object[] formatArgs); + void Error(string message); + + /// Logs a formatted message with severity Error. + void Error(string format, params object[] formatArgs); /// Logs a message and an associated exception with severity Error. - void Error(Exception exception, string message, params object[] formatArgs); + void Error(Exception exception, string message); } } diff --git a/src/csharp/Grpc.Core/VersionInfo.cs b/src/csharp/Grpc.Core/VersionInfo.cs index eda821bc312..e9ec30e9238 100644 --- a/src/csharp/Grpc.Core/VersionInfo.cs +++ b/src/csharp/Grpc.Core/VersionInfo.cs @@ -41,6 +41,6 @@ namespace Grpc.Core /// /// Current version of gRPC C# /// - public const string CurrentVersion = "0.7.0"; + public const string CurrentVersion = "0.7.1"; } } diff --git a/src/csharp/Grpc.IntegrationTesting/InteropClient.cs b/src/csharp/Grpc.IntegrationTesting/InteropClient.cs index 0884c6ea60a..616093d4aeb 100644 --- a/src/csharp/Grpc.IntegrationTesting/InteropClient.cs +++ b/src/csharp/Grpc.IntegrationTesting/InteropClient.cs @@ -131,7 +131,7 @@ namespace Grpc.IntegrationTesting var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions); TestService.TestServiceClient client = new TestService.TestServiceClient(channel); await RunTestCaseAsync(client, options); - channel.ShutdownAsync().Wait(); + await channel.ShutdownAsync(); } private async Task RunTestCaseAsync(TestService.TestServiceClient client, ClientOptions options) diff --git a/src/csharp/Grpc.IntegrationTesting/proto/test.proto b/src/csharp/Grpc.IntegrationTesting/proto/test.proto index f9e0d2a0396..5496f72af07 100644 --- a/src/csharp/Grpc.IntegrationTesting/proto/test.proto +++ b/src/csharp/Grpc.IntegrationTesting/proto/test.proto @@ -44,7 +44,6 @@ service TestService { rpc EmptyCall(grpc.testing.Empty) returns (grpc.testing.Empty); // One request followed by one response. - // TODO(Issue 527): Describe required server behavior. rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // One request followed by a sequence of responses (streamed download). diff --git a/src/csharp/build_packages.bat b/src/csharp/build_packages.bat index ea2206e7606..a3505b1e012 100644 --- a/src/csharp/build_packages.bat +++ b/src/csharp/build_packages.bat @@ -1,12 +1,12 @@ @rem Builds gRPC NuGet packages @rem Current package versions -set VERSION=0.7.0 -set CORE_VERSION=0.11.0 +set VERSION=0.7.1 +set CORE_VERSION=0.11.1 set PROTOBUF_VERSION=3.0.0-alpha4 @rem Packages that depend on prerelease packages (like Google.Protobuf) need to have prerelease suffix as well. -set VERSION_WITH_BETA=0.7.0-beta +set VERSION_WITH_BETA=%VERSION%-beta @rem Adjust the location of nuget.exe set NUGET=C:\nuget\nuget.exe diff --git a/src/node/binding.gyp b/src/node/binding.gyp index 734dc8410b5..a6440309324 100644 --- a/src/node/binding.gyp +++ b/src/node/binding.gyp @@ -8,7 +8,6 @@ '-std=c++0x', '-Wall', '-pthread', - '-pedantic', '-g', '-zdefs', '-Werror', diff --git a/src/node/ext/byte_buffer.cc b/src/node/ext/byte_buffer.cc index 7eff11c2b34..e1786ddba7e 100644 --- a/src/node/ext/byte_buffer.cc +++ b/src/node/ext/byte_buffer.cc @@ -44,15 +44,16 @@ namespace grpc { namespace node { + using v8::Context; using v8::Function; -using v8::Handle; +using v8::Local; using v8::Object; using v8::Number; using v8::Value; -grpc_byte_buffer *BufferToByteBuffer(Handle buffer) { - NanScope(); +grpc_byte_buffer *BufferToByteBuffer(Local buffer) { + Nan::HandleScope scope; int length = ::node::Buffer::Length(buffer); char *data = ::node::Buffer::Data(buffer); gpr_slice slice = gpr_slice_malloc(length); @@ -62,10 +63,10 @@ grpc_byte_buffer *BufferToByteBuffer(Handle buffer) { return byte_buffer; } -Handle ByteBufferToBuffer(grpc_byte_buffer *buffer) { - NanEscapableScope(); +Local ByteBufferToBuffer(grpc_byte_buffer *buffer) { + Nan::EscapableHandleScope scope; if (buffer == NULL) { - return NanEscapeScope(NanNull()); + return scope.Escape(Nan::Null()); } size_t length = grpc_byte_buffer_length(buffer); char *result = reinterpret_cast(calloc(length, sizeof(char))); @@ -77,21 +78,22 @@ Handle ByteBufferToBuffer(grpc_byte_buffer *buffer) { memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next)); offset += GPR_SLICE_LENGTH(next); } - return NanEscapeScope(MakeFastBuffer(NanNewBufferHandle(result, length))); + return scope.Escape(MakeFastBuffer( + Nan::NewBuffer(result, length).ToLocalChecked())); } -Handle MakeFastBuffer(Handle slowBuffer) { - NanEscapableScope(); - Handle globalObj = NanGetCurrentContext()->Global(); - Handle bufferConstructor = Handle::Cast( - globalObj->Get(NanNew("Buffer"))); - Handle consArgs[3] = { +Local MakeFastBuffer(Local slowBuffer) { + Nan::EscapableHandleScope scope; + Local globalObj = Nan::GetCurrentContext()->Global(); + Local bufferConstructor = Local::Cast( + globalObj->Get(Nan::New("Buffer").ToLocalChecked())); + Local consArgs[3] = { slowBuffer, - NanNew(::node::Buffer::Length(slowBuffer)), - NanNew(0) + Nan::New(::node::Buffer::Length(slowBuffer)), + Nan::New(0) }; - Handle fastBuffer = bufferConstructor->NewInstance(3, consArgs); - return NanEscapeScope(fastBuffer); + Local fastBuffer = bufferConstructor->NewInstance(3, consArgs); + return scope.Escape(fastBuffer); } } // namespace node } // namespace grpc diff --git a/src/node/ext/byte_buffer.h b/src/node/ext/byte_buffer.h index 5083674d394..55bc0ab3771 100644 --- a/src/node/ext/byte_buffer.h +++ b/src/node/ext/byte_buffer.h @@ -45,14 +45,14 @@ namespace node { /* Convert a Node.js Buffer to grpc_byte_buffer. Requires that ::node::Buffer::HasInstance(buffer) */ -grpc_byte_buffer *BufferToByteBuffer(v8::Handle buffer); +grpc_byte_buffer *BufferToByteBuffer(v8::Local buffer); /* Convert a grpc_byte_buffer to a Node.js Buffer */ -v8::Handle ByteBufferToBuffer(grpc_byte_buffer *buffer); +v8::Local ByteBufferToBuffer(grpc_byte_buffer *buffer); /* Convert a ::node::Buffer to a fast Buffer, as defined in the Node Buffer documentation */ -v8::Handle MakeFastBuffer(v8::Handle slowBuffer); +v8::Local MakeFastBuffer(v8::Local slowBuffer); } // namespace node } // namespace grpc diff --git a/src/node/ext/call.cc b/src/node/ext/call.cc index 560869e6fa4..b08a9f96d81 100644 --- a/src/node/ext/call.cc +++ b/src/node/ext/call.cc @@ -54,52 +54,61 @@ using std::vector; namespace grpc { namespace node { +using Nan::Callback; +using Nan::EscapableHandleScope; +using Nan::HandleScope; +using Nan::Maybe; +using Nan::MaybeLocal; +using Nan::ObjectWrap; +using Nan::Persistent; +using Nan::Utf8String; + using v8::Array; using v8::Boolean; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; -using v8::Handle; -using v8::HandleScope; using v8::Integer; using v8::Local; using v8::Number; using v8::Object; using v8::ObjectTemplate; -using v8::Persistent; using v8::Uint32; using v8::String; using v8::Value; -NanCallback *Call::constructor; +Callback *Call::constructor; Persistent Call::fun_tpl; bool EndsWith(const char *str, const char *substr) { return strcmp(str+strlen(str)-strlen(substr), substr) == 0; } -bool CreateMetadataArray(Handle metadata, grpc_metadata_array *array, +bool CreateMetadataArray(Local metadata, grpc_metadata_array *array, shared_ptr resources) { - NanScope(); + HandleScope scope; grpc_metadata_array_init(array); - Handle keys(metadata->GetOwnPropertyNames()); + Local keys = Nan::GetOwnPropertyNames(metadata).ToLocalChecked(); for (unsigned int i = 0; i < keys->Length(); i++) { - Handle current_key(keys->Get(i)->ToString()); - if (!metadata->Get(current_key)->IsArray()) { + Local current_key = Nan::To( + Nan::Get(keys, i).ToLocalChecked()).ToLocalChecked(); + Local value_array = Nan::Get(metadata, current_key).ToLocalChecked(); + if (!value_array->IsArray()) { return false; } - array->capacity += Local::Cast(metadata->Get(current_key))->Length(); + array->capacity += Local::Cast(value_array)->Length(); } array->metadata = reinterpret_cast( gpr_malloc(array->capacity * sizeof(grpc_metadata))); for (unsigned int i = 0; i < keys->Length(); i++) { - Handle current_key(keys->Get(i)->ToString()); - NanUtf8String *utf8_key = new NanUtf8String(current_key); - resources->strings.push_back(unique_ptr(utf8_key)); - Handle values = Local::Cast(metadata->Get(current_key)); + Local current_key(keys->Get(i)->ToString()); + Utf8String *utf8_key = new Utf8String(current_key); + resources->strings.push_back(unique_ptr(utf8_key)); + Local values = Local::Cast( + Nan::Get(metadata, current_key).ToLocalChecked()); for (unsigned int j = 0; j < values->Length(); j++) { - Handle value = values->Get(j); + Local value = Nan::Get(values, j).ToLocalChecked(); grpc_metadata *current = &array->metadata[array->count]; current->key = **utf8_key; // Only allow binary headers for "-bin" keys @@ -107,18 +116,16 @@ bool CreateMetadataArray(Handle metadata, grpc_metadata_array *array, if (::node::Buffer::HasInstance(value)) { current->value = ::node::Buffer::Data(value); current->value_length = ::node::Buffer::Length(value); - Persistent *handle = new Persistent(); - NanAssignPersistent(*handle, value); - resources->handles.push_back(unique_ptr( - new PersistentHolder(handle))); + PersistentValue *handle = new PersistentValue(value); + resources->handles.push_back(unique_ptr(handle)); } else { return false; } } else { if (value->IsString()) { - Handle string_value = value->ToString(); - NanUtf8String *utf8_value = new NanUtf8String(string_value); - resources->strings.push_back(unique_ptr(utf8_value)); + Local string_value = Nan::To(value).ToLocalChecked(); + Utf8String *utf8_value = new Utf8String(string_value); + resources->strings.push_back(unique_ptr(utf8_value)); current->value = **utf8_value; current->value_length = string_value->Length(); } else { @@ -131,8 +138,8 @@ bool CreateMetadataArray(Handle metadata, grpc_metadata_array *array, return true; } -Handle ParseMetadata(const grpc_metadata_array *metadata_array) { - NanEscapableScope(); +Local ParseMetadata(const grpc_metadata_array *metadata_array) { + EscapableHandleScope scope; grpc_metadata *metadata_elements = metadata_array->metadata; size_t length = metadata_array->count; std::map size_map; @@ -142,49 +149,62 @@ Handle ParseMetadata(const grpc_metadata_array *metadata_array) { const char *key = metadata_elements[i].key; if (size_map.count(key)) { size_map[key] += 1; + } else { + size_map[key] = 1; } index_map[key] = 0; } - Handle metadata_object = NanNew(); + Local metadata_object = Nan::New(); for (unsigned int i = 0; i < length; i++) { grpc_metadata* elem = &metadata_elements[i]; - Handle key_string = NanNew(elem->key); - Handle array; - if (metadata_object->Has(key_string)) { - array = Handle::Cast(metadata_object->Get(key_string)); + Local key_string = Nan::New(elem->key).ToLocalChecked(); + Local array; + MaybeLocal maybe_array = Nan::Get(metadata_object, key_string); + if (maybe_array.IsEmpty() || !maybe_array.ToLocalChecked()->IsArray()) { + array = Nan::New(size_map[elem->key]); + Nan::Set(metadata_object, key_string, array); } else { - array = NanNew(size_map[elem->key]); - metadata_object->Set(key_string, array); + array = Local::Cast(maybe_array.ToLocalChecked()); } if (EndsWith(elem->key, "-bin")) { - array->Set(index_map[elem->key], - NanNewBufferHandle(elem->value, elem->value_length)); + Nan::Set(array, index_map[elem->key], + Nan::CopyBuffer(elem->value, + elem->value_length).ToLocalChecked()); } else { - array->Set(index_map[elem->key], NanNew(elem->value)); + Nan::Set(array, index_map[elem->key], + Nan::New(elem->value).ToLocalChecked()); } index_map[elem->key] += 1; } - return NanEscapeScope(metadata_object); + return scope.Escape(metadata_object); } -Handle Op::GetOpType() const { - NanEscapableScope(); - return NanEscapeScope(NanNew(GetTypeString())); +Local Op::GetOpType() const { + EscapableHandleScope scope; + return scope.Escape(Nan::New(GetTypeString()).ToLocalChecked()); +} + +Op::~Op() { } class SendMetadataOp : public Op { public: - Handle GetNodeValue() const { - NanEscapableScope(); - return NanEscapeScope(NanTrue()); + Local GetNodeValue() const { + EscapableHandleScope scope; + return scope.Escape(Nan::True()); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { if (!value->IsObject()) { return false; } grpc_metadata_array array; - if (!CreateMetadataArray(value->ToObject(), &array, resources)) { + MaybeLocal maybe_metadata = Nan::To(value); + if (maybe_metadata.IsEmpty()) { + return false; + } + if (!CreateMetadataArray(maybe_metadata.ToLocalChecked(), + &array, resources)) { return false; } out->data.send_initial_metadata.count = array.count; @@ -199,27 +219,28 @@ class SendMetadataOp : public Op { class SendMessageOp : public Op { public: - Handle GetNodeValue() const { - NanEscapableScope(); - return NanEscapeScope(NanTrue()); + Local GetNodeValue() const { + EscapableHandleScope scope; + return scope.Escape(Nan::True()); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { if (!::node::Buffer::HasInstance(value)) { return false; } - Handle object_value = value->ToObject(); - if (object_value->HasOwnProperty(NanNew("grpcWriteFlags"))) { - Handle flag_value = object_value->Get(NanNew("grpcWriteFlags")); + Local object_value = Nan::To(value).ToLocalChecked(); + MaybeLocal maybe_flag_value = Nan::Get( + object_value, Nan::New("grpcWriteFlags").ToLocalChecked()); + if (!maybe_flag_value.IsEmpty()) { + Local flag_value = maybe_flag_value.ToLocalChecked(); if (flag_value->IsUint32()) { - out->flags = flag_value->Uint32Value() & GRPC_WRITE_USED_MASK; + Maybe maybe_flag = Nan::To(flag_value); + out->flags = maybe_flag.FromMaybe(0) & GRPC_WRITE_USED_MASK; } } out->data.send_message = BufferToByteBuffer(value); - Persistent *handle = new Persistent(); - NanAssignPersistent(*handle, value); - resources->handles.push_back(unique_ptr( - new PersistentHolder(handle))); + PersistentValue *handle = new PersistentValue(value); + resources->handles.push_back(unique_ptr(handle)); return true; } protected: @@ -230,11 +251,11 @@ class SendMessageOp : public Op { class SendClientCloseOp : public Op { public: - Handle GetNodeValue() const { - NanEscapableScope(); - return NanEscapeScope(NanTrue()); + Local GetNodeValue() const { + EscapableHandleScope scope; + return scope.Escape(Nan::True()); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { return true; } @@ -246,39 +267,55 @@ class SendClientCloseOp : public Op { class SendServerStatusOp : public Op { public: - Handle GetNodeValue() const { - NanEscapableScope(); - return NanEscapeScope(NanTrue()); + Local GetNodeValue() const { + EscapableHandleScope scope; + return scope.Escape(Nan::True()); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { if (!value->IsObject()) { return false; } - Handle server_status = value->ToObject(); - if (!server_status->Get(NanNew("metadata"))->IsObject()) { + Local server_status = Nan::To(value).ToLocalChecked(); + MaybeLocal maybe_metadata = Nan::Get( + server_status, Nan::New("metadata").ToLocalChecked()); + if (maybe_metadata.IsEmpty()) { return false; } - if (!server_status->Get(NanNew("code"))->IsUint32()) { + if (!maybe_metadata.ToLocalChecked()->IsObject()) { return false; } - if (!server_status->Get(NanNew("details"))->IsString()) { + Local metadata = Nan::To( + maybe_metadata.ToLocalChecked()).ToLocalChecked(); + MaybeLocal maybe_code = Nan::Get(server_status, + Nan::New("code").ToLocalChecked()); + if (maybe_code.IsEmpty()) { return false; } + if (!maybe_code.ToLocalChecked()->IsUint32()) { + return false; + } + uint32_t code = Nan::To(maybe_code.ToLocalChecked()).FromJust(); + MaybeLocal maybe_details = Nan::Get( + server_status, Nan::New("details").ToLocalChecked()); + if (maybe_details.IsEmpty()) { + return false; + } + if (!maybe_details.ToLocalChecked()->IsString()) { + return false; + } + Local details = Nan::To( + maybe_details.ToLocalChecked()).ToLocalChecked(); grpc_metadata_array array; - if (!CreateMetadataArray(server_status->Get(NanNew("metadata"))-> - ToObject(), - &array, resources)) { + if (!CreateMetadataArray(metadata, &array, resources)) { return false; } out->data.send_status_from_server.trailing_metadata_count = array.count; out->data.send_status_from_server.trailing_metadata = array.metadata; out->data.send_status_from_server.status = - static_cast( - server_status->Get(NanNew("code"))->Uint32Value()); - NanUtf8String *str = new NanUtf8String( - server_status->Get(NanNew("details"))); - resources->strings.push_back(unique_ptr(str)); + static_cast(code); + Utf8String *str = new Utf8String(details); + resources->strings.push_back(unique_ptr(str)); out->data.send_status_from_server.status_details = **str; return true; } @@ -298,12 +335,12 @@ class GetMetadataOp : public Op { grpc_metadata_array_destroy(&recv_metadata); } - Handle GetNodeValue() const { - NanEscapableScope(); - return NanEscapeScope(ParseMetadata(&recv_metadata)); + Local GetNodeValue() const { + EscapableHandleScope scope; + return scope.Escape(ParseMetadata(&recv_metadata)); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { out->data.recv_initial_metadata = &recv_metadata; return true; @@ -325,15 +362,15 @@ class ReadMessageOp : public Op { } ~ReadMessageOp() { if (recv_message != NULL) { - gpr_free(recv_message); + grpc_byte_buffer_destroy(recv_message); } } - Handle GetNodeValue() const { - NanEscapableScope(); - return NanEscapeScope(ByteBufferToBuffer(recv_message)); + Local GetNodeValue() const { + EscapableHandleScope scope; + return scope.Escape(ByteBufferToBuffer(recv_message)); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { out->data.recv_message = &recv_message; return true; @@ -361,7 +398,7 @@ class ClientStatusOp : public Op { gpr_free(status_details); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { out->data.recv_status_on_client.trailing_metadata = &metadata_array; out->data.recv_status_on_client.status = &status; @@ -370,15 +407,18 @@ class ClientStatusOp : public Op { return true; } - Handle GetNodeValue() const { - NanEscapableScope(); - Handle status_obj = NanNew(); - status_obj->Set(NanNew("code"), NanNew(status)); + Local GetNodeValue() const { + EscapableHandleScope scope; + Local status_obj = Nan::New(); + Nan::Set(status_obj, Nan::New("code").ToLocalChecked(), + Nan::New(status)); if (status_details != NULL) { - status_obj->Set(NanNew("details"), NanNew(status_details)); + Nan::Set(status_obj, Nan::New("details").ToLocalChecked(), + Nan::New(status_details).ToLocalChecked()); } - status_obj->Set(NanNew("metadata"), ParseMetadata(&metadata_array)); - return NanEscapeScope(status_obj); + Nan::Set(status_obj, Nan::New("metadata").ToLocalChecked(), + ParseMetadata(&metadata_array)); + return scope.Escape(status_obj); } protected: std::string GetTypeString() const { @@ -393,12 +433,12 @@ class ClientStatusOp : public Op { class ServerCloseResponseOp : public Op { public: - Handle GetNodeValue() const { - NanEscapableScope(); - return NanEscapeScope(NanNew(cancelled)); + Local GetNodeValue() const { + EscapableHandleScope scope; + return scope.Escape(Nan::New(cancelled)); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { out->data.recv_close_on_server.cancelled = &cancelled; return true; @@ -413,7 +453,7 @@ class ServerCloseResponseOp : public Op { int cancelled; }; -tag::tag(NanCallback *callback, OpVec *ops, +tag::tag(Callback *callback, OpVec *ops, shared_ptr resources) : callback(callback), ops(ops), resources(resources){ } @@ -423,19 +463,19 @@ tag::~tag() { delete ops; } -Handle GetTagNodeValue(void *tag) { - NanEscapableScope(); +Local GetTagNodeValue(void *tag) { + EscapableHandleScope scope; struct tag *tag_struct = reinterpret_cast(tag); - Handle tag_obj = NanNew(); + Local tag_obj = Nan::New(); for (vector >::iterator it = tag_struct->ops->begin(); it != tag_struct->ops->end(); ++it) { Op *op_ptr = it->get(); - tag_obj->Set(op_ptr->GetOpType(), op_ptr->GetNodeValue()); + Nan::Set(tag_obj, op_ptr->GetOpType(), op_ptr->GetNodeValue()); } - return NanEscapeScope(tag_obj); + return scope.Escape(tag_obj); } -NanCallback *GetTagCallback(void *tag) { +Callback *GetTagCallback(void *tag) { struct tag *tag_struct = reinterpret_cast(tag); return tag_struct->callback; } @@ -452,140 +492,149 @@ Call::~Call() { grpc_call_destroy(wrapped_call); } -void Call::Init(Handle exports) { - NanScope(); - Local tpl = NanNew(New); - tpl->SetClassName(NanNew("Call")); +void Call::Init(Local exports) { + HandleScope scope; + Local tpl = Nan::New(New); + tpl->SetClassName(Nan::New("Call").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); - NanSetPrototypeTemplate(tpl, "startBatch", - NanNew(StartBatch)->GetFunction()); - NanSetPrototypeTemplate(tpl, "cancel", - NanNew(Cancel)->GetFunction()); - NanSetPrototypeTemplate( - tpl, "cancelWithStatus", - NanNew(CancelWithStatus)->GetFunction()); - NanSetPrototypeTemplate(tpl, "getPeer", - NanNew(GetPeer)->GetFunction()); - NanAssignPersistent(fun_tpl, tpl); - Handle ctr = tpl->GetFunction(); - exports->Set(NanNew("Call"), ctr); - constructor = new NanCallback(ctr); + Nan::SetPrototypeMethod(tpl, "startBatch", StartBatch); + Nan::SetPrototypeMethod(tpl, "cancel", Cancel); + Nan::SetPrototypeMethod(tpl, "cancelWithStatus", CancelWithStatus); + Nan::SetPrototypeMethod(tpl, "getPeer", GetPeer); + fun_tpl.Reset(tpl); + Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); + Nan::Set(exports, Nan::New("Call").ToLocalChecked(), ctr); + constructor = new Callback(ctr); } -bool Call::HasInstance(Handle val) { - NanScope(); - return NanHasInstance(fun_tpl, val); +bool Call::HasInstance(Local val) { + HandleScope scope; + return Nan::New(fun_tpl)->HasInstance(val); } -Handle Call::WrapStruct(grpc_call *call) { - NanEscapableScope(); +Local Call::WrapStruct(grpc_call *call) { + EscapableHandleScope scope; if (call == NULL) { - return NanEscapeScope(NanNull()); + return scope.Escape(Nan::Null()); } const int argc = 1; - Handle argv[argc] = {NanNew(reinterpret_cast(call))}; - return NanEscapeScope(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = {Nan::New( + reinterpret_cast(call))}; + MaybeLocal maybe_instance = Nan::NewInstance( + constructor->GetFunction(), argc, argv); + if (maybe_instance.IsEmpty()) { + return scope.Escape(Nan::Null()); + } else { + return scope.Escape(maybe_instance.ToLocalChecked()); + } } NAN_METHOD(Call::New) { - NanScope(); - - if (args.IsConstructCall()) { + if (info.IsConstructCall()) { Call *call; - if (args[0]->IsExternal()) { - Handle ext = args[0].As(); + if (info[0]->IsExternal()) { + Local ext = info[0].As(); // This option is used for wrapping an existing call grpc_call *call_value = reinterpret_cast(ext->Value()); call = new Call(call_value); } else { - if (!Channel::HasInstance(args[0])) { - return NanThrowTypeError("Call's first argument must be a Channel"); + if (!Channel::HasInstance(info[0])) { + return Nan::ThrowTypeError("Call's first argument must be a Channel"); } - if (!args[1]->IsString()) { - return NanThrowTypeError("Call's second argument must be a string"); + if (!info[1]->IsString()) { + return Nan::ThrowTypeError("Call's second argument must be a string"); } - if (!(args[2]->IsNumber() || args[2]->IsDate())) { - return NanThrowTypeError( + if (!(info[2]->IsNumber() || info[2]->IsDate())) { + return Nan::ThrowTypeError( "Call's third argument must be a date or a number"); } // These arguments are at the end because they are optional grpc_call *parent_call = NULL; - if (Call::HasInstance(args[4])) { - Call *parent_obj = ObjectWrap::Unwrap(args[4]->ToObject()); + if (Call::HasInstance(info[4])) { + Call *parent_obj = ObjectWrap::Unwrap( + Nan::To(info[4]).ToLocalChecked()); parent_call = parent_obj->wrapped_call; - } else if (!(args[4]->IsUndefined() || args[4]->IsNull())) { - return NanThrowTypeError( + } else if (!(info[4]->IsUndefined() || info[4]->IsNull())) { + return Nan::ThrowTypeError( "Call's fifth argument must be another call, if provided"); } gpr_uint32 propagate_flags = GRPC_PROPAGATE_DEFAULTS; - if (args[5]->IsUint32()) { - propagate_flags = args[5]->Uint32Value(); - } else if (!(args[5]->IsUndefined() || args[5]->IsNull())) { - return NanThrowTypeError( + if (info[5]->IsUint32()) { + propagate_flags = Nan::To(info[5]).FromJust(); + } else if (!(info[5]->IsUndefined() || info[5]->IsNull())) { + return Nan::ThrowTypeError( "Call's sixth argument must be propagate flags, if provided"); } - Handle channel_object = args[0]->ToObject(); + Local channel_object = Nan::To(info[0]).ToLocalChecked(); Channel *channel = ObjectWrap::Unwrap(channel_object); if (channel->GetWrappedChannel() == NULL) { - return NanThrowError("Call cannot be created from a closed channel"); + return Nan::ThrowError("Call cannot be created from a closed channel"); } - NanUtf8String method(args[1]); - double deadline = args[2]->NumberValue(); + Utf8String method(info[1]); + double deadline = Nan::To(info[2]).FromJust(); grpc_channel *wrapped_channel = channel->GetWrappedChannel(); grpc_call *wrapped_call; - if (args[3]->IsString()) { - NanUtf8String host_override(args[3]); + if (info[3]->IsString()) { + Utf8String host_override(info[3]); wrapped_call = grpc_channel_create_call( wrapped_channel, parent_call, propagate_flags, CompletionQueueAsyncWorker::GetQueue(), *method, *host_override, MillisecondsToTimespec(deadline), NULL); - } else if (args[3]->IsUndefined() || args[3]->IsNull()) { + } else if (info[3]->IsUndefined() || info[3]->IsNull()) { wrapped_call = grpc_channel_create_call( wrapped_channel, parent_call, propagate_flags, CompletionQueueAsyncWorker::GetQueue(), *method, NULL, MillisecondsToTimespec(deadline), NULL); } else { - return NanThrowTypeError("Call's fourth argument must be a string"); + return Nan::ThrowTypeError("Call's fourth argument must be a string"); } call = new Call(wrapped_call); - args.This()->SetHiddenValue(NanNew("channel_"), channel_object); + info.This()->SetHiddenValue(Nan::New("channel_").ToLocalChecked(), + channel_object); } - call->Wrap(args.This()); - NanReturnValue(args.This()); + call->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); } else { const int argc = 4; - Local argv[argc] = {args[0], args[1], args[2], args[3]}; - NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = {info[0], info[1], info[2], info[3]}; + MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance( + argc, argv); + if (maybe_instance.IsEmpty()) { + // There's probably a pending exception + return; + } else { + info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); + } } } NAN_METHOD(Call::StartBatch) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("startBatch can only be called on Call objects"); + if (!Call::HasInstance(info.This())) { + return Nan::ThrowTypeError("startBatch can only be called on Call objects"); } - if (!args[0]->IsObject()) { - return NanThrowError("startBatch's first argument must be an object"); + if (!info[0]->IsObject()) { + return Nan::ThrowError("startBatch's first argument must be an object"); } - if (!args[1]->IsFunction()) { - return NanThrowError("startBatch's second argument must be a callback"); + if (!info[1]->IsFunction()) { + return Nan::ThrowError("startBatch's second argument must be a callback"); } - Handle callback_func = args[1].As(); - Call *call = ObjectWrap::Unwrap(args.This()); + Local callback_func = info[1].As(); + Call *call = ObjectWrap::Unwrap(info.This()); shared_ptr resources(new Resources); - Handle obj = args[0]->ToObject(); - Handle keys = obj->GetOwnPropertyNames(); + Local obj = Nan::To(info[0]).ToLocalChecked(); + Local keys = Nan::GetOwnPropertyNames(obj).ToLocalChecked(); size_t nops = keys->Length(); vector ops(nops); unique_ptr op_vector(new OpVec()); for (unsigned int i = 0; i < nops; i++) { unique_ptr op; - if (!keys->Get(i)->IsUint32()) { - return NanThrowError( + MaybeLocal maybe_key = Nan::Get(keys, i); + if (maybe_key.IsEmpty() || (!maybe_key.ToLocalChecked()->IsUint32())) { + return Nan::ThrowError( "startBatch's first argument's keys must be integers"); } - uint32_t type = keys->Get(i)->Uint32Value(); + uint32_t type = Nan::To(maybe_key.ToLocalChecked()).FromJust(); ops[i].op = static_cast(type); ops[i].flags = 0; ops[i].reserved = NULL; @@ -615,67 +664,64 @@ NAN_METHOD(Call::StartBatch) { op.reset(new ServerCloseResponseOp()); break; default: - return NanThrowError("Argument object had an unrecognized key"); + return Nan::ThrowError("Argument object had an unrecognized key"); } if (!op->ParseOp(obj->Get(type), &ops[i], resources)) { - return NanThrowTypeError("Incorrectly typed arguments to startBatch"); + return Nan::ThrowTypeError("Incorrectly typed arguments to startBatch"); } op_vector->push_back(std::move(op)); } - NanCallback *callback = new NanCallback(callback_func); + Callback *callback = new Callback(callback_func); grpc_call_error error = grpc_call_start_batch( call->wrapped_call, &ops[0], nops, new struct tag( callback, op_vector.release(), resources), NULL); if (error != GRPC_CALL_OK) { - return NanThrowError(nanErrorWithCode("startBatch failed", error)); + return Nan::ThrowError(nanErrorWithCode("startBatch failed", error)); } CompletionQueueAsyncWorker::Next(); - NanReturnUndefined(); } NAN_METHOD(Call::Cancel) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("cancel can only be called on Call objects"); + if (!Call::HasInstance(info.This())) { + return Nan::ThrowTypeError("cancel can only be called on Call objects"); } - Call *call = ObjectWrap::Unwrap(args.This()); + Call *call = ObjectWrap::Unwrap(info.This()); grpc_call_error error = grpc_call_cancel(call->wrapped_call, NULL); if (error != GRPC_CALL_OK) { - return NanThrowError(nanErrorWithCode("cancel failed", error)); + return Nan::ThrowError(nanErrorWithCode("cancel failed", error)); } - NanReturnUndefined(); } NAN_METHOD(Call::CancelWithStatus) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("cancel can only be called on Call objects"); + Nan::HandleScope scope; + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("cancel can only be called on Call objects"); } - if (!args[0]->IsUint32()) { - return NanThrowTypeError( + if (!info[0]->IsUint32()) { + return Nan::ThrowTypeError( "cancelWithStatus's first argument must be a status code"); } - if (!args[1]->IsString()) { - return NanThrowTypeError( + if (!info[1]->IsString()) { + return Nan::ThrowTypeError( "cancelWithStatus's second argument must be a string"); } - Call *call = ObjectWrap::Unwrap(args.This()); - grpc_status_code code = static_cast(args[0]->Uint32Value()); - NanUtf8String details(args[0]); + Call *call = ObjectWrap::Unwrap(info.This()); + grpc_status_code code = static_cast( + Nan::To(info[0]).FromJust()); + Utf8String details(info[0]); grpc_call_cancel_with_status(call->wrapped_call, code, *details, NULL); - NanReturnUndefined(); } NAN_METHOD(Call::GetPeer) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("getPeer can only be called on Call objects"); + Nan::HandleScope scope; + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("getPeer can only be called on Call objects"); } - Call *call = ObjectWrap::Unwrap(args.This()); + Call *call = ObjectWrap::Unwrap(info.This()); char *peer = grpc_call_get_peer(call->wrapped_call); - Handle peer_value = NanNew(peer); + Local peer_value = Nan::New(peer).ToLocalChecked(); gpr_free(peer); - NanReturnValue(peer_value); + info.GetReturnValue().Set(peer_value); } } // namespace node diff --git a/src/node/ext/call.h b/src/node/ext/call.h index 89f81dcf4dc..2f8e1f17aae 100644 --- a/src/node/ext/call.h +++ b/src/node/ext/call.h @@ -51,6 +51,8 @@ namespace node { using std::unique_ptr; using std::shared_ptr; +typedef Nan::Persistent> PersistentValue; + /** * Helper function for throwing errors with a grpc_call_error value. * Modified from the answer by Gus Goose to @@ -58,69 +60,54 @@ using std::shared_ptr; */ inline v8::Local nanErrorWithCode(const char *msg, grpc_call_error code) { - NanEscapableScope(); - v8::Local err = NanError(msg).As(); - err->Set(NanNew("code"), NanNew(code)); - return NanEscapeScope(err); + Nan::EscapableHandleScope scope; + v8::Local err = Nan::Error(msg).As(); + Nan::Set(err, Nan::New("code").ToLocalChecked(), Nan::New(code)); + return scope.Escape(err); } -v8::Handle ParseMetadata(const grpc_metadata_array *metadata_array); - -class PersistentHolder { - public: - explicit PersistentHolder(v8::Persistent *persist) : - persist(persist) { - } - - ~PersistentHolder() { - NanDisposePersistent(*persist); - delete persist; - } - - private: - v8::Persistent *persist; -}; +v8::Local ParseMetadata(const grpc_metadata_array *metadata_array); struct Resources { - std::vector > strings; - std::vector > handles; + std::vector > strings; + std::vector > handles; }; class Op { public: - virtual v8::Handle GetNodeValue() const = 0; - virtual bool ParseOp(v8::Handle value, grpc_op *out, + virtual v8::Local GetNodeValue() const = 0; + virtual bool ParseOp(v8::Local value, grpc_op *out, shared_ptr resources) = 0; - v8::Handle GetOpType() const; + virtual ~Op(); + v8::Local GetOpType() const; protected: virtual std::string GetTypeString() const = 0; }; typedef std::vector> OpVec; - struct tag { - tag(NanCallback *callback, OpVec *ops, + tag(Nan::Callback *callback, OpVec *ops, shared_ptr resources); ~tag(); - NanCallback *callback; + Nan::Callback *callback; OpVec *ops; shared_ptr resources; }; -v8::Handle GetTagNodeValue(void *tag); +v8::Local GetTagNodeValue(void *tag); -NanCallback *GetTagCallback(void *tag); +Nan::Callback *GetTagCallback(void *tag); void DestroyTag(void *tag); /* Wrapper class for grpc_call structs. */ -class Call : public ::node::ObjectWrap { +class Call : public Nan::ObjectWrap { public: - static void Init(v8::Handle exports); - static bool HasInstance(v8::Handle val); + static void Init(v8::Local exports); + static bool HasInstance(v8::Local val); /* Wrap a grpc_call struct in a javascript object */ - static v8::Handle WrapStruct(grpc_call *call); + static v8::Local WrapStruct(grpc_call *call); private: explicit Call(grpc_call *call); @@ -135,9 +122,9 @@ class Call : public ::node::ObjectWrap { static NAN_METHOD(Cancel); static NAN_METHOD(CancelWithStatus); static NAN_METHOD(GetPeer); - static NanCallback *constructor; + static Nan::Callback *constructor; // Used for typechecking instances of this javascript class - static v8::Persistent fun_tpl; + static Nan::Persistent fun_tpl; grpc_call *wrapped_call; }; diff --git a/src/node/ext/channel.cc b/src/node/ext/channel.cc index 9aed96bbf5a..6eb1e776884 100644 --- a/src/node/ext/channel.cc +++ b/src/node/ext/channel.cc @@ -48,21 +48,27 @@ namespace grpc { namespace node { +using Nan::Callback; +using Nan::EscapableHandleScope; +using Nan::HandleScope; +using Nan::Maybe; +using Nan::MaybeLocal; +using Nan::ObjectWrap; +using Nan::Persistent; +using Nan::Utf8String; + using v8::Array; using v8::Exception; using v8::Function; using v8::FunctionTemplate; -using v8::Handle; -using v8::HandleScope; using v8::Integer; using v8::Local; using v8::Number; using v8::Object; -using v8::Persistent; using v8::String; using v8::Value; -NanCallback *Channel::constructor; +Callback *Channel::constructor; Persistent Channel::fun_tpl; Channel::Channel(grpc_channel *channel) : wrapped_channel(channel) {} @@ -73,88 +79,89 @@ Channel::~Channel() { } } -void Channel::Init(Handle exports) { - NanScope(); - Local tpl = NanNew(New); - tpl->SetClassName(NanNew("Channel")); +void Channel::Init(Local exports) { + Nan::HandleScope scope; + Local tpl = Nan::New(New); + tpl->SetClassName(Nan::New("Channel").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); - NanSetPrototypeTemplate(tpl, "close", - NanNew(Close)->GetFunction()); - NanSetPrototypeTemplate(tpl, "getTarget", - NanNew(GetTarget)->GetFunction()); - NanSetPrototypeTemplate( - tpl, "getConnectivityState", - NanNew(GetConnectivityState)->GetFunction()); - NanSetPrototypeTemplate( - tpl, "watchConnectivityState", - NanNew(WatchConnectivityState)->GetFunction()); - NanAssignPersistent(fun_tpl, tpl); - Handle ctr = tpl->GetFunction(); - constructor = new NanCallback(ctr); - exports->Set(NanNew("Channel"), ctr); + Nan::SetPrototypeMethod(tpl, "close", Close); + Nan::SetPrototypeMethod(tpl, "getTarget", GetTarget); + Nan::SetPrototypeMethod(tpl, "getConnectivityState", GetConnectivityState); + Nan::SetPrototypeMethod(tpl, "watchConnectivityState", + WatchConnectivityState); + fun_tpl.Reset(tpl); + Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); + Nan::Set(exports, Nan::New("Channel").ToLocalChecked(), ctr); + constructor = new Callback(ctr); } -bool Channel::HasInstance(Handle val) { - NanScope(); - return NanHasInstance(fun_tpl, val); +bool Channel::HasInstance(Local val) { + HandleScope scope; + return Nan::New(fun_tpl)->HasInstance(val); } grpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; } NAN_METHOD(Channel::New) { - NanScope(); - - if (args.IsConstructCall()) { - if (!args[0]->IsString()) { - return NanThrowTypeError( + if (info.IsConstructCall()) { + if (!info[0]->IsString()) { + return Nan::ThrowTypeError( "Channel expects a string, a credential and an object"); } grpc_channel *wrapped_channel; // Owned by the Channel object - NanUtf8String host(args[0]); + Utf8String host(info[0]); grpc_credentials *creds; - if (!Credentials::HasInstance(args[1])) { - return NanThrowTypeError( + if (!Credentials::HasInstance(info[1])) { + return Nan::ThrowTypeError( "Channel's second argument must be a credential"); } Credentials *creds_object = ObjectWrap::Unwrap( - args[1]->ToObject()); + Nan::To(info[1]).ToLocalChecked()); creds = creds_object->GetWrappedCredentials(); grpc_channel_args *channel_args_ptr; - if (args[2]->IsUndefined()) { + if (info[2]->IsUndefined()) { channel_args_ptr = NULL; wrapped_channel = grpc_insecure_channel_create(*host, NULL, NULL); - } else if (args[2]->IsObject()) { - Handle args_hash(args[2]->ToObject()->Clone()); - Handle keys(args_hash->GetOwnPropertyNames()); + } else if (info[2]->IsObject()) { + Local args_hash = Nan::To(info[2]).ToLocalChecked(); + Local keys(Nan::GetOwnPropertyNames(args_hash).ToLocalChecked()); grpc_channel_args channel_args; channel_args.num_args = keys->Length(); channel_args.args = reinterpret_cast( calloc(channel_args.num_args, sizeof(grpc_arg))); /* These are used to keep all strings until then end of the block, then destroy them */ - std::vector key_strings(keys->Length()); - std::vector value_strings(keys->Length()); + std::vector key_strings(keys->Length()); + std::vector value_strings(keys->Length()); for (unsigned int i = 0; i < channel_args.num_args; i++) { - Handle current_key(keys->Get(i)->ToString()); - Handle current_value(args_hash->Get(current_key)); - key_strings[i] = new NanUtf8String(current_key); + MaybeLocal maybe_key = Nan::To( + Nan::Get(keys, i).ToLocalChecked()); + if (maybe_key.IsEmpty()) { + free(channel_args.args); + return Nan::ThrowTypeError("Arg keys must be strings"); + } + Local current_key = maybe_key.ToLocalChecked(); + Local current_value = Nan::Get(args_hash, + current_key).ToLocalChecked(); + key_strings[i] = new Nan::Utf8String(current_key); channel_args.args[i].key = **key_strings[i]; if (current_value->IsInt32()) { channel_args.args[i].type = GRPC_ARG_INTEGER; - channel_args.args[i].value.integer = current_value->Int32Value(); + channel_args.args[i].value.integer = Nan::To( + current_value).FromJust(); } else if (current_value->IsString()) { channel_args.args[i].type = GRPC_ARG_STRING; - value_strings[i] = new NanUtf8String(current_value); + value_strings[i] = new Nan::Utf8String(current_value); channel_args.args[i].value.string = **value_strings[i]; } else { free(channel_args.args); - return NanThrowTypeError("Arg values must be strings"); + return Nan::ThrowTypeError("Arg values must be strings"); } } channel_args_ptr = &channel_args; } else { - return NanThrowTypeError("Channel expects a string and an object"); + return Nan::ThrowTypeError("Channel expects a string and an object"); } if (creds == NULL) { wrapped_channel = grpc_insecure_channel_create(*host, channel_args_ptr, @@ -167,73 +174,79 @@ NAN_METHOD(Channel::New) { free(channel_args_ptr->args); } Channel *channel = new Channel(wrapped_channel); - channel->Wrap(args.This()); - NanReturnValue(args.This()); + channel->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + return; } else { const int argc = 3; - Local argv[argc] = {args[0], args[1], args[2]}; - NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = {info[0], info[1], info[2]}; + MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance( + argc, argv); + if (maybe_instance.IsEmpty()) { + // There's probably a pending exception + return; + } else { + info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); + } } } NAN_METHOD(Channel::Close) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("close can only be called on Channel objects"); + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("close can only be called on Channel objects"); } - Channel *channel = ObjectWrap::Unwrap(args.This()); + Channel *channel = ObjectWrap::Unwrap(info.This()); if (channel->wrapped_channel != NULL) { grpc_channel_destroy(channel->wrapped_channel); channel->wrapped_channel = NULL; } - NanReturnUndefined(); } NAN_METHOD(Channel::GetTarget) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("getTarget can only be called on Channel objects"); + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("getTarget can only be called on Channel objects"); } - Channel *channel = ObjectWrap::Unwrap(args.This()); - NanReturnValue(NanNew(grpc_channel_get_target(channel->wrapped_channel))); + Channel *channel = ObjectWrap::Unwrap(info.This()); + info.GetReturnValue().Set(Nan::New( + grpc_channel_get_target(channel->wrapped_channel)).ToLocalChecked()); } NAN_METHOD(Channel::GetConnectivityState) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError( + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError( "getConnectivityState can only be called on Channel objects"); } - Channel *channel = ObjectWrap::Unwrap(args.This()); - int try_to_connect = (int)args[0]->Equals(NanTrue()); - NanReturnValue(grpc_channel_check_connectivity_state(channel->wrapped_channel, - try_to_connect)); + Channel *channel = ObjectWrap::Unwrap(info.This()); + int try_to_connect = (int)info[0]->Equals(Nan::True()); + info.GetReturnValue().Set( + grpc_channel_check_connectivity_state(channel->wrapped_channel, + try_to_connect)); } NAN_METHOD(Channel::WatchConnectivityState) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError( + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError( "watchConnectivityState can only be called on Channel objects"); } - if (!args[0]->IsUint32()) { - return NanThrowTypeError( + if (!info[0]->IsUint32()) { + return Nan::ThrowTypeError( "watchConnectivityState's first argument must be a channel state"); } - if (!(args[1]->IsNumber() || args[1]->IsDate())) { - return NanThrowTypeError( + if (!(info[1]->IsNumber() || info[1]->IsDate())) { + return Nan::ThrowTypeError( "watchConnectivityState's second argument must be a date or a number"); } - if (!args[2]->IsFunction()) { - return NanThrowTypeError( + if (!info[2]->IsFunction()) { + return Nan::ThrowTypeError( "watchConnectivityState's third argument must be a callback"); } grpc_connectivity_state last_state = - static_cast(args[0]->Uint32Value()); - double deadline = args[1]->NumberValue(); - Handle callback_func = args[2].As(); - NanCallback *callback = new NanCallback(callback_func); - Channel *channel = ObjectWrap::Unwrap(args.This()); + static_cast( + Nan::To(info[0]).FromJust()); + double deadline = Nan::To(info[1]).FromJust(); + Local callback_func = info[2].As(); + Nan::Callback *callback = new Callback(callback_func); + Channel *channel = ObjectWrap::Unwrap(info.This()); unique_ptr ops(new OpVec()); grpc_channel_watch_connectivity_state( channel->wrapped_channel, last_state, MillisecondsToTimespec(deadline), @@ -242,7 +255,6 @@ NAN_METHOD(Channel::WatchConnectivityState) { ops.release(), shared_ptr(nullptr))); CompletionQueueAsyncWorker::Next(); - NanReturnUndefined(); } } // namespace node diff --git a/src/node/ext/channel.h b/src/node/ext/channel.h index 458f71d0930..0062fd03f4a 100644 --- a/src/node/ext/channel.h +++ b/src/node/ext/channel.h @@ -42,10 +42,10 @@ namespace grpc { namespace node { /* Wrapper class for grpc_channel structs */ -class Channel : public ::node::ObjectWrap { +class Channel : public Nan::ObjectWrap { public: - static void Init(v8::Handle exports); - static bool HasInstance(v8::Handle val); + static void Init(v8::Local exports); + static bool HasInstance(v8::Local val); /* This is used to typecheck javascript objects before converting them to this type */ static v8::Persistent prototype; @@ -66,8 +66,8 @@ class Channel : public ::node::ObjectWrap { static NAN_METHOD(GetTarget); static NAN_METHOD(GetConnectivityState); static NAN_METHOD(WatchConnectivityState); - static NanCallback *constructor; - static v8::Persistent fun_tpl; + static Nan::Callback *constructor; + static Nan::Persistent fun_tpl; grpc_channel *wrapped_channel; }; diff --git a/src/node/ext/completion_queue_async_worker.cc b/src/node/ext/completion_queue_async_worker.cc index bf2cd946a5c..3a79f7c45d0 100644 --- a/src/node/ext/completion_queue_async_worker.cc +++ b/src/node/ext/completion_queue_async_worker.cc @@ -46,9 +46,8 @@ namespace node { const int max_queue_threads = 2; using v8::Function; -using v8::Handle; +using v8::Local; using v8::Object; -using v8::Persistent; using v8::Value; grpc_completion_queue *CompletionQueueAsyncWorker::queue; @@ -57,7 +56,7 @@ int CompletionQueueAsyncWorker::current_threads; int CompletionQueueAsyncWorker::waiting_next_calls; CompletionQueueAsyncWorker::CompletionQueueAsyncWorker() - : NanAsyncWorker(NULL) {} + : Nan::AsyncWorker(NULL) {} CompletionQueueAsyncWorker::~CompletionQueueAsyncWorker() {} @@ -72,42 +71,42 @@ void CompletionQueueAsyncWorker::Execute() { grpc_completion_queue *CompletionQueueAsyncWorker::GetQueue() { return queue; } void CompletionQueueAsyncWorker::Next() { - NanScope(); + Nan::HandleScope scope; if (current_threads < max_queue_threads) { CompletionQueueAsyncWorker *worker = new CompletionQueueAsyncWorker(); - NanAsyncQueueWorker(worker); + Nan::AsyncQueueWorker(worker); } else { waiting_next_calls += 1; } } -void CompletionQueueAsyncWorker::Init(Handle exports) { - NanScope(); +void CompletionQueueAsyncWorker::Init(Local exports) { + Nan::HandleScope scope; current_threads = 0; waiting_next_calls = 0; queue = grpc_completion_queue_create(NULL); } void CompletionQueueAsyncWorker::HandleOKCallback() { - NanScope(); + Nan::HandleScope scope; if (waiting_next_calls > 0) { waiting_next_calls -= 1; CompletionQueueAsyncWorker *worker = new CompletionQueueAsyncWorker(); - NanAsyncQueueWorker(worker); + Nan::AsyncQueueWorker(worker); } else { current_threads -= 1; } - NanCallback *callback = GetTagCallback(result.tag); - Handle argv[] = {NanNull(), GetTagNodeValue(result.tag)}; + Nan::Callback *callback = GetTagCallback(result.tag); + Local argv[] = {Nan::Null(), GetTagNodeValue(result.tag)}; callback->Call(2, argv); DestroyTag(result.tag); } void CompletionQueueAsyncWorker::HandleErrorCallback() { - NanScope(); - NanCallback *callback = GetTagCallback(result.tag); - Handle argv[] = {NanError(ErrorMessage())}; + Nan::HandleScope scope; + Nan::Callback *callback = GetTagCallback(result.tag); + Local argv[] = {Nan::Error(ErrorMessage())}; callback->Call(1, argv); diff --git a/src/node/ext/completion_queue_async_worker.h b/src/node/ext/completion_queue_async_worker.h index 27fedf2fce4..6e541167658 100644 --- a/src/node/ext/completion_queue_async_worker.h +++ b/src/node/ext/completion_queue_async_worker.h @@ -42,7 +42,7 @@ namespace node { /* A worker that asynchronously calls completion_queue_next, and queues onto the node event loop a call to the function stored in the event's tag. */ -class CompletionQueueAsyncWorker : public NanAsyncWorker { +class CompletionQueueAsyncWorker : public Nan::AsyncWorker { public: CompletionQueueAsyncWorker(); @@ -59,7 +59,7 @@ class CompletionQueueAsyncWorker : public NanAsyncWorker { static void Next(); /* Initialize the CompletionQueueAsyncWorker class */ - static void Init(v8::Handle exports); + static void Init(v8::Local exports); protected: /* Called when Execute has succeeded (completed without setting an error diff --git a/src/node/ext/credentials.cc b/src/node/ext/credentials.cc index c3b04dcea75..4f41c92f6a7 100644 --- a/src/node/ext/credentials.cc +++ b/src/node/ext/credentials.cc @@ -41,20 +41,26 @@ namespace grpc { namespace node { +using Nan::Callback; +using Nan::EscapableHandleScope; +using Nan::HandleScope; +using Nan::Maybe; +using Nan::MaybeLocal; +using Nan::ObjectWrap; +using Nan::Persistent; +using Nan::Utf8String; + using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; -using v8::Handle; -using v8::HandleScope; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; -using v8::Persistent; using v8::Value; -NanCallback *Credentials::constructor; +Nan::Callback *Credentials::constructor; Persistent Credentials::fun_tpl; Credentials::Credentials(grpc_credentials *credentials) @@ -64,40 +70,52 @@ Credentials::~Credentials() { grpc_credentials_release(wrapped_credentials); } -void Credentials::Init(Handle exports) { - NanScope(); - Local tpl = NanNew(New); - tpl->SetClassName(NanNew("Credentials")); +void Credentials::Init(Local exports) { + HandleScope scope; + Local tpl = Nan::New(New); + tpl->SetClassName(Nan::New("Credentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); - NanAssignPersistent(fun_tpl, tpl); - Handle ctr = tpl->GetFunction(); - ctr->Set(NanNew("createDefault"), - NanNew(CreateDefault)->GetFunction()); - ctr->Set(NanNew("createSsl"), - NanNew(CreateSsl)->GetFunction()); - ctr->Set(NanNew("createComposite"), - NanNew(CreateComposite)->GetFunction()); - ctr->Set(NanNew("createGce"), - NanNew(CreateGce)->GetFunction()); - ctr->Set(NanNew("createIam"), - NanNew(CreateIam)->GetFunction()); - ctr->Set(NanNew("createInsecure"), - NanNew(CreateInsecure)->GetFunction()); - constructor = new NanCallback(ctr); - exports->Set(NanNew("Credentials"), ctr); + fun_tpl.Reset(tpl); + Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); + Nan::Set(ctr, Nan::New("createDefault").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateDefault)).ToLocalChecked()); + Nan::Set(ctr, Nan::New("createSsl").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateSsl)).ToLocalChecked()); + Nan::Set(ctr, Nan::New("createComposite").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateComposite)).ToLocalChecked()); + Nan::Set(ctr, Nan::New("createGce").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateGce)).ToLocalChecked()); + Nan::Set(ctr, Nan::New("createIam").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateIam)).ToLocalChecked()); + Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateInsecure)).ToLocalChecked()); + Nan::Set(exports, Nan::New("Credentials").ToLocalChecked(), ctr); + constructor = new Nan::Callback(ctr); } -bool Credentials::HasInstance(Handle val) { - NanScope(); - return NanHasInstance(fun_tpl, val); +bool Credentials::HasInstance(Local val) { + HandleScope scope; + return Nan::New(fun_tpl)->HasInstance(val); } -Handle Credentials::WrapStruct(grpc_credentials *credentials) { - NanEscapableScope(); +Local Credentials::WrapStruct(grpc_credentials *credentials) { + EscapableHandleScope scope; const int argc = 1; - Handle argv[argc] = { - NanNew(reinterpret_cast(credentials))}; - return NanEscapeScope(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = { + Nan::New(reinterpret_cast(credentials))}; + MaybeLocal maybe_instance = Nan::NewInstance( + constructor->GetFunction(), argc, argv); + if (maybe_instance.IsEmpty()) { + return scope.Escape(Nan::Null()); + } else { + return scope.Escape(maybe_instance.ToLocalChecked()); + } } grpc_credentials *Credentials::GetWrappedCredentials() { @@ -105,115 +123,123 @@ grpc_credentials *Credentials::GetWrappedCredentials() { } NAN_METHOD(Credentials::New) { - NanScope(); - - if (args.IsConstructCall()) { - if (!args[0]->IsExternal()) { - return NanThrowTypeError( + if (info.IsConstructCall()) { + if (!info[0]->IsExternal()) { + return Nan::ThrowTypeError( "Credentials can only be created with the provided functions"); } - Handle ext = args[0].As(); + Local ext = info[0].As(); grpc_credentials *creds_value = reinterpret_cast(ext->Value()); Credentials *credentials = new Credentials(creds_value); - credentials->Wrap(args.This()); - NanReturnValue(args.This()); + credentials->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + return; } else { const int argc = 1; - Local argv[argc] = {args[0]}; - NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = {info[0]}; + MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance( + argc, argv); + if (maybe_instance.IsEmpty()) { + // There's probably a pending exception + return; + } else { + info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); + } } } NAN_METHOD(Credentials::CreateDefault) { - NanScope(); grpc_credentials *creds = grpc_google_default_credentials_create(); if (creds == NULL) { - NanReturnNull(); + info.GetReturnValue().SetNull(); + } else { + info.GetReturnValue().Set(WrapStruct(creds)); } - NanReturnValue(WrapStruct(creds)); } NAN_METHOD(Credentials::CreateSsl) { - NanScope(); char *root_certs = NULL; grpc_ssl_pem_key_cert_pair key_cert_pair = {NULL, NULL}; - if (::node::Buffer::HasInstance(args[0])) { - root_certs = ::node::Buffer::Data(args[0]); - } else if (!(args[0]->IsNull() || args[0]->IsUndefined())) { - return NanThrowTypeError("createSsl's first argument must be a Buffer"); + if (::node::Buffer::HasInstance(info[0])) { + root_certs = ::node::Buffer::Data(info[0]); + } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { + return Nan::ThrowTypeError("createSsl's first argument must be a Buffer"); } - if (::node::Buffer::HasInstance(args[1])) { - key_cert_pair.private_key = ::node::Buffer::Data(args[1]); - } else if (!(args[1]->IsNull() || args[1]->IsUndefined())) { - return NanThrowTypeError( + if (::node::Buffer::HasInstance(info[1])) { + key_cert_pair.private_key = ::node::Buffer::Data(info[1]); + } else if (!(info[1]->IsNull() || info[1]->IsUndefined())) { + return Nan::ThrowTypeError( "createSSl's second argument must be a Buffer if provided"); } - if (::node::Buffer::HasInstance(args[2])) { - key_cert_pair.cert_chain = ::node::Buffer::Data(args[2]); - } else if (!(args[2]->IsNull() || args[2]->IsUndefined())) { - return NanThrowTypeError( + if (::node::Buffer::HasInstance(info[2])) { + key_cert_pair.cert_chain = ::node::Buffer::Data(info[2]); + } else if (!(info[2]->IsNull() || info[2]->IsUndefined())) { + return Nan::ThrowTypeError( "createSSl's third argument must be a Buffer if provided"); } grpc_credentials *creds = grpc_ssl_credentials_create( root_certs, key_cert_pair.private_key == NULL ? NULL : &key_cert_pair, NULL); if (creds == NULL) { - NanReturnNull(); + info.GetReturnValue().SetNull(); + } else { + info.GetReturnValue().Set(WrapStruct(creds)); } - NanReturnValue(WrapStruct(creds)); } NAN_METHOD(Credentials::CreateComposite) { - NanScope(); - if (!HasInstance(args[0])) { - return NanThrowTypeError( + if (!HasInstance(info[0])) { + return Nan::ThrowTypeError( "createComposite's first argument must be a Credentials object"); } - if (!HasInstance(args[1])) { - return NanThrowTypeError( + if (!HasInstance(info[1])) { + return Nan::ThrowTypeError( "createComposite's second argument must be a Credentials object"); } - Credentials *creds1 = ObjectWrap::Unwrap(args[0]->ToObject()); - Credentials *creds2 = ObjectWrap::Unwrap(args[1]->ToObject()); + Credentials *creds1 = ObjectWrap::Unwrap( + Nan::To(info[0]).ToLocalChecked()); + Credentials *creds2 = ObjectWrap::Unwrap( + Nan::To(info[1]).ToLocalChecked()); grpc_credentials *creds = grpc_composite_credentials_create( creds1->wrapped_credentials, creds2->wrapped_credentials, NULL); if (creds == NULL) { - NanReturnNull(); + info.GetReturnValue().SetNull(); + } else { + info.GetReturnValue().Set(WrapStruct(creds)); } - NanReturnValue(WrapStruct(creds)); } NAN_METHOD(Credentials::CreateGce) { - NanScope(); + Nan::HandleScope scope; grpc_credentials *creds = grpc_google_compute_engine_credentials_create(NULL); if (creds == NULL) { - NanReturnNull(); + info.GetReturnValue().SetNull(); + } else { + info.GetReturnValue().Set(WrapStruct(creds)); } - NanReturnValue(WrapStruct(creds)); } NAN_METHOD(Credentials::CreateIam) { - NanScope(); - if (!args[0]->IsString()) { - return NanThrowTypeError("createIam's first argument must be a string"); + if (!info[0]->IsString()) { + return Nan::ThrowTypeError("createIam's first argument must be a string"); } - if (!args[1]->IsString()) { - return NanThrowTypeError("createIam's second argument must be a string"); + if (!info[1]->IsString()) { + return Nan::ThrowTypeError("createIam's second argument must be a string"); } - NanUtf8String auth_token(args[0]); - NanUtf8String auth_selector(args[1]); + Utf8String auth_token(info[0]); + Utf8String auth_selector(info[1]); grpc_credentials *creds = grpc_google_iam_credentials_create(*auth_token, *auth_selector, NULL); if (creds == NULL) { - NanReturnNull(); + info.GetReturnValue().SetNull(); + } else { + info.GetReturnValue().Set(WrapStruct(creds)); } - NanReturnValue(WrapStruct(creds)); } NAN_METHOD(Credentials::CreateInsecure) { - NanScope(); - NanReturnValue(WrapStruct(NULL)); + info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node diff --git a/src/node/ext/credentials.h b/src/node/ext/credentials.h index 62957e61c3e..1b211175d45 100644 --- a/src/node/ext/credentials.h +++ b/src/node/ext/credentials.h @@ -43,12 +43,12 @@ namespace grpc { namespace node { /* Wrapper class for grpc_credentials structs */ -class Credentials : public ::node::ObjectWrap { +class Credentials : public Nan::ObjectWrap { public: - static void Init(v8::Handle exports); - static bool HasInstance(v8::Handle val); + static void Init(v8::Local exports); + static bool HasInstance(v8::Local val); /* Wrap a grpc_credentials struct in a javascript object */ - static v8::Handle WrapStruct(grpc_credentials *credentials); + static v8::Local WrapStruct(grpc_credentials *credentials); /* Returns the grpc_credentials struct that this object wraps */ grpc_credentials *GetWrappedCredentials(); @@ -69,9 +69,9 @@ class Credentials : public ::node::ObjectWrap { static NAN_METHOD(CreateFake); static NAN_METHOD(CreateIam); static NAN_METHOD(CreateInsecure); - static NanCallback *constructor; + static Nan::Callback *constructor; // Used for typechecking instances of this javascript class - static v8::Persistent fun_tpl; + static Nan::Persistent fun_tpl; grpc_credentials *wrapped_credentials; }; diff --git a/src/node/ext/node_grpc.cc b/src/node/ext/node_grpc.cc index 0cf30da9228..caca0fc4522 100644 --- a/src/node/ext/node_grpc.cc +++ b/src/node/ext/node_grpc.cc @@ -43,171 +43,194 @@ #include "credentials.h" #include "server_credentials.h" -using v8::Handle; +using v8::Local; using v8::Value; using v8::Object; using v8::Uint32; using v8::String; -void InitStatusConstants(Handle exports) { - NanScope(); - Handle status = NanNew(); - exports->Set(NanNew("status"), status); - Handle OK(NanNew(GRPC_STATUS_OK)); - status->Set(NanNew("OK"), OK); - Handle CANCELLED(NanNew(GRPC_STATUS_CANCELLED)); - status->Set(NanNew("CANCELLED"), CANCELLED); - Handle UNKNOWN(NanNew(GRPC_STATUS_UNKNOWN)); - status->Set(NanNew("UNKNOWN"), UNKNOWN); - Handle INVALID_ARGUMENT( - NanNew(GRPC_STATUS_INVALID_ARGUMENT)); - status->Set(NanNew("INVALID_ARGUMENT"), INVALID_ARGUMENT); - Handle DEADLINE_EXCEEDED( - NanNew(GRPC_STATUS_DEADLINE_EXCEEDED)); - status->Set(NanNew("DEADLINE_EXCEEDED"), DEADLINE_EXCEEDED); - Handle NOT_FOUND(NanNew(GRPC_STATUS_NOT_FOUND)); - status->Set(NanNew("NOT_FOUND"), NOT_FOUND); - Handle ALREADY_EXISTS( - NanNew(GRPC_STATUS_ALREADY_EXISTS)); - status->Set(NanNew("ALREADY_EXISTS"), ALREADY_EXISTS); - Handle PERMISSION_DENIED( - NanNew(GRPC_STATUS_PERMISSION_DENIED)); - status->Set(NanNew("PERMISSION_DENIED"), PERMISSION_DENIED); - Handle UNAUTHENTICATED( - NanNew(GRPC_STATUS_UNAUTHENTICATED)); - status->Set(NanNew("UNAUTHENTICATED"), UNAUTHENTICATED); - Handle RESOURCE_EXHAUSTED( - NanNew(GRPC_STATUS_RESOURCE_EXHAUSTED)); - status->Set(NanNew("RESOURCE_EXHAUSTED"), RESOURCE_EXHAUSTED); - Handle FAILED_PRECONDITION( - NanNew(GRPC_STATUS_FAILED_PRECONDITION)); - status->Set(NanNew("FAILED_PRECONDITION"), FAILED_PRECONDITION); - Handle ABORTED(NanNew(GRPC_STATUS_ABORTED)); - status->Set(NanNew("ABORTED"), ABORTED); - Handle OUT_OF_RANGE( - NanNew(GRPC_STATUS_OUT_OF_RANGE)); - status->Set(NanNew("OUT_OF_RANGE"), OUT_OF_RANGE); - Handle UNIMPLEMENTED( - NanNew(GRPC_STATUS_UNIMPLEMENTED)); - status->Set(NanNew("UNIMPLEMENTED"), UNIMPLEMENTED); - Handle INTERNAL(NanNew(GRPC_STATUS_INTERNAL)); - status->Set(NanNew("INTERNAL"), INTERNAL); - Handle UNAVAILABLE(NanNew(GRPC_STATUS_UNAVAILABLE)); - status->Set(NanNew("UNAVAILABLE"), UNAVAILABLE); - Handle DATA_LOSS(NanNew(GRPC_STATUS_DATA_LOSS)); - status->Set(NanNew("DATA_LOSS"), DATA_LOSS); +void InitStatusConstants(Local exports) { + Nan::HandleScope scope; + Local status = Nan::New(); + Nan::Set(exports, Nan::New("status").ToLocalChecked(), status); + Local OK(Nan::New(GRPC_STATUS_OK)); + Nan::Set(status, Nan::New("OK").ToLocalChecked(), OK); + Local CANCELLED(Nan::New(GRPC_STATUS_CANCELLED)); + Nan::Set(status, Nan::New("CANCELLED").ToLocalChecked(), CANCELLED); + Local UNKNOWN(Nan::New(GRPC_STATUS_UNKNOWN)); + Nan::Set(status, Nan::New("UNKNOWN").ToLocalChecked(), UNKNOWN); + Local INVALID_ARGUMENT( + Nan::New(GRPC_STATUS_INVALID_ARGUMENT)); + Nan::Set(status, Nan::New("INVALID_ARGUMENT").ToLocalChecked(), + INVALID_ARGUMENT); + Local DEADLINE_EXCEEDED( + Nan::New(GRPC_STATUS_DEADLINE_EXCEEDED)); + Nan::Set(status, Nan::New("DEADLINE_EXCEEDED").ToLocalChecked(), + DEADLINE_EXCEEDED); + Local NOT_FOUND(Nan::New(GRPC_STATUS_NOT_FOUND)); + Nan::Set(status, Nan::New("NOT_FOUND").ToLocalChecked(), NOT_FOUND); + Local ALREADY_EXISTS( + Nan::New(GRPC_STATUS_ALREADY_EXISTS)); + Nan::Set(status, Nan::New("ALREADY_EXISTS").ToLocalChecked(), ALREADY_EXISTS); + Local PERMISSION_DENIED( + Nan::New(GRPC_STATUS_PERMISSION_DENIED)); + Nan::Set(status, Nan::New("PERMISSION_DENIED").ToLocalChecked(), + PERMISSION_DENIED); + Local UNAUTHENTICATED( + Nan::New(GRPC_STATUS_UNAUTHENTICATED)); + Nan::Set(status, Nan::New("UNAUTHENTICATED").ToLocalChecked(), + UNAUTHENTICATED); + Local RESOURCE_EXHAUSTED( + Nan::New(GRPC_STATUS_RESOURCE_EXHAUSTED)); + Nan::Set(status, Nan::New("RESOURCE_EXHAUSTED").ToLocalChecked(), + RESOURCE_EXHAUSTED); + Local FAILED_PRECONDITION( + Nan::New(GRPC_STATUS_FAILED_PRECONDITION)); + Nan::Set(status, Nan::New("FAILED_PRECONDITION").ToLocalChecked(), + FAILED_PRECONDITION); + Local ABORTED(Nan::New(GRPC_STATUS_ABORTED)); + Nan::Set(status, Nan::New("ABORTED").ToLocalChecked(), ABORTED); + Local OUT_OF_RANGE( + Nan::New(GRPC_STATUS_OUT_OF_RANGE)); + Nan::Set(status, Nan::New("OUT_OF_RANGE").ToLocalChecked(), OUT_OF_RANGE); + Local UNIMPLEMENTED( + Nan::New(GRPC_STATUS_UNIMPLEMENTED)); + Nan::Set(status, Nan::New("UNIMPLEMENTED").ToLocalChecked(), UNIMPLEMENTED); + Local INTERNAL(Nan::New(GRPC_STATUS_INTERNAL)); + Nan::Set(status, Nan::New("INTERNAL").ToLocalChecked(), INTERNAL); + Local UNAVAILABLE(Nan::New(GRPC_STATUS_UNAVAILABLE)); + Nan::Set(status, Nan::New("UNAVAILABLE").ToLocalChecked(), UNAVAILABLE); + Local DATA_LOSS(Nan::New(GRPC_STATUS_DATA_LOSS)); + Nan::Set(status, Nan::New("DATA_LOSS").ToLocalChecked(), DATA_LOSS); } -void InitCallErrorConstants(Handle exports) { - NanScope(); - Handle call_error = NanNew(); - exports->Set(NanNew("callError"), call_error); - Handle OK(NanNew(GRPC_CALL_OK)); - call_error->Set(NanNew("OK"), OK); - Handle ERROR(NanNew(GRPC_CALL_ERROR)); - call_error->Set(NanNew("ERROR"), ERROR); - Handle NOT_ON_SERVER( - NanNew(GRPC_CALL_ERROR_NOT_ON_SERVER)); - call_error->Set(NanNew("NOT_ON_SERVER"), NOT_ON_SERVER); - Handle NOT_ON_CLIENT( - NanNew(GRPC_CALL_ERROR_NOT_ON_CLIENT)); - call_error->Set(NanNew("NOT_ON_CLIENT"), NOT_ON_CLIENT); - Handle ALREADY_INVOKED( - NanNew(GRPC_CALL_ERROR_ALREADY_INVOKED)); - call_error->Set(NanNew("ALREADY_INVOKED"), ALREADY_INVOKED); - Handle NOT_INVOKED( - NanNew(GRPC_CALL_ERROR_NOT_INVOKED)); - call_error->Set(NanNew("NOT_INVOKED"), NOT_INVOKED); - Handle ALREADY_FINISHED( - NanNew(GRPC_CALL_ERROR_ALREADY_FINISHED)); - call_error->Set(NanNew("ALREADY_FINISHED"), ALREADY_FINISHED); - Handle TOO_MANY_OPERATIONS( - NanNew(GRPC_CALL_ERROR_TOO_MANY_OPERATIONS)); - call_error->Set(NanNew("TOO_MANY_OPERATIONS"), TOO_MANY_OPERATIONS); - Handle INVALID_FLAGS( - NanNew(GRPC_CALL_ERROR_INVALID_FLAGS)); - call_error->Set(NanNew("INVALID_FLAGS"), INVALID_FLAGS); +void InitCallErrorConstants(Local exports) { + Nan::HandleScope scope; + Local call_error = Nan::New(); + Nan::Set(exports, Nan::New("callError").ToLocalChecked(), call_error); + Local OK(Nan::New(GRPC_CALL_OK)); + Nan::Set(call_error, Nan::New("OK").ToLocalChecked(), OK); + Local ERROR(Nan::New(GRPC_CALL_ERROR)); + Nan::Set(call_error, Nan::New("ERROR").ToLocalChecked(), ERROR); + Local NOT_ON_SERVER( + Nan::New(GRPC_CALL_ERROR_NOT_ON_SERVER)); + Nan::Set(call_error, Nan::New("NOT_ON_SERVER").ToLocalChecked(), + NOT_ON_SERVER); + Local NOT_ON_CLIENT( + Nan::New(GRPC_CALL_ERROR_NOT_ON_CLIENT)); + Nan::Set(call_error, Nan::New("NOT_ON_CLIENT").ToLocalChecked(), + NOT_ON_CLIENT); + Local ALREADY_INVOKED( + Nan::New(GRPC_CALL_ERROR_ALREADY_INVOKED)); + Nan::Set(call_error, Nan::New("ALREADY_INVOKED").ToLocalChecked(), + ALREADY_INVOKED); + Local NOT_INVOKED( + Nan::New(GRPC_CALL_ERROR_NOT_INVOKED)); + Nan::Set(call_error, Nan::New("NOT_INVOKED").ToLocalChecked(), NOT_INVOKED); + Local ALREADY_FINISHED( + Nan::New(GRPC_CALL_ERROR_ALREADY_FINISHED)); + Nan::Set(call_error, Nan::New("ALREADY_FINISHED").ToLocalChecked(), + ALREADY_FINISHED); + Local TOO_MANY_OPERATIONS( + Nan::New(GRPC_CALL_ERROR_TOO_MANY_OPERATIONS)); + Nan::Set(call_error, Nan::New("TOO_MANY_OPERATIONS").ToLocalChecked(), + TOO_MANY_OPERATIONS); + Local INVALID_FLAGS( + Nan::New(GRPC_CALL_ERROR_INVALID_FLAGS)); + Nan::Set(call_error, Nan::New("INVALID_FLAGS").ToLocalChecked(), + INVALID_FLAGS); } -void InitOpTypeConstants(Handle exports) { - NanScope(); - Handle op_type = NanNew(); - exports->Set(NanNew("opType"), op_type); - Handle SEND_INITIAL_METADATA( - NanNew(GRPC_OP_SEND_INITIAL_METADATA)); - op_type->Set(NanNew("SEND_INITIAL_METADATA"), SEND_INITIAL_METADATA); - Handle SEND_MESSAGE( - NanNew(GRPC_OP_SEND_MESSAGE)); - op_type->Set(NanNew("SEND_MESSAGE"), SEND_MESSAGE); - Handle SEND_CLOSE_FROM_CLIENT( - NanNew(GRPC_OP_SEND_CLOSE_FROM_CLIENT)); - op_type->Set(NanNew("SEND_CLOSE_FROM_CLIENT"), SEND_CLOSE_FROM_CLIENT); - Handle SEND_STATUS_FROM_SERVER( - NanNew(GRPC_OP_SEND_STATUS_FROM_SERVER)); - op_type->Set(NanNew("SEND_STATUS_FROM_SERVER"), SEND_STATUS_FROM_SERVER); - Handle RECV_INITIAL_METADATA( - NanNew(GRPC_OP_RECV_INITIAL_METADATA)); - op_type->Set(NanNew("RECV_INITIAL_METADATA"), RECV_INITIAL_METADATA); - Handle RECV_MESSAGE( - NanNew(GRPC_OP_RECV_MESSAGE)); - op_type->Set(NanNew("RECV_MESSAGE"), RECV_MESSAGE); - Handle RECV_STATUS_ON_CLIENT( - NanNew(GRPC_OP_RECV_STATUS_ON_CLIENT)); - op_type->Set(NanNew("RECV_STATUS_ON_CLIENT"), RECV_STATUS_ON_CLIENT); - Handle RECV_CLOSE_ON_SERVER( - NanNew(GRPC_OP_RECV_CLOSE_ON_SERVER)); - op_type->Set(NanNew("RECV_CLOSE_ON_SERVER"), RECV_CLOSE_ON_SERVER); +void InitOpTypeConstants(Local exports) { + Nan::HandleScope scope; + Local op_type = Nan::New(); + Nan::Set(exports, Nan::New("opType").ToLocalChecked(), op_type); + Local SEND_INITIAL_METADATA( + Nan::New(GRPC_OP_SEND_INITIAL_METADATA)); + Nan::Set(op_type, Nan::New("SEND_INITIAL_METADATA").ToLocalChecked(), + SEND_INITIAL_METADATA); + Local SEND_MESSAGE( + Nan::New(GRPC_OP_SEND_MESSAGE)); + Nan::Set(op_type, Nan::New("SEND_MESSAGE").ToLocalChecked(), SEND_MESSAGE); + Local SEND_CLOSE_FROM_CLIENT( + Nan::New(GRPC_OP_SEND_CLOSE_FROM_CLIENT)); + Nan::Set(op_type, Nan::New("SEND_CLOSE_FROM_CLIENT").ToLocalChecked(), + SEND_CLOSE_FROM_CLIENT); + Local SEND_STATUS_FROM_SERVER( + Nan::New(GRPC_OP_SEND_STATUS_FROM_SERVER)); + Nan::Set(op_type, Nan::New("SEND_STATUS_FROM_SERVER").ToLocalChecked(), + SEND_STATUS_FROM_SERVER); + Local RECV_INITIAL_METADATA( + Nan::New(GRPC_OP_RECV_INITIAL_METADATA)); + Nan::Set(op_type, Nan::New("RECV_INITIAL_METADATA").ToLocalChecked(), + RECV_INITIAL_METADATA); + Local RECV_MESSAGE( + Nan::New(GRPC_OP_RECV_MESSAGE)); + Nan::Set(op_type, Nan::New("RECV_MESSAGE").ToLocalChecked(), RECV_MESSAGE); + Local RECV_STATUS_ON_CLIENT( + Nan::New(GRPC_OP_RECV_STATUS_ON_CLIENT)); + Nan::Set(op_type, Nan::New("RECV_STATUS_ON_CLIENT").ToLocalChecked(), + RECV_STATUS_ON_CLIENT); + Local RECV_CLOSE_ON_SERVER( + Nan::New(GRPC_OP_RECV_CLOSE_ON_SERVER)); + Nan::Set(op_type, Nan::New("RECV_CLOSE_ON_SERVER").ToLocalChecked(), + RECV_CLOSE_ON_SERVER); } -void InitPropagateConstants(Handle exports) { - NanScope(); - Handle propagate = NanNew(); - exports->Set(NanNew("propagate"), propagate); - Handle DEADLINE(NanNew(GRPC_PROPAGATE_DEADLINE)); - propagate->Set(NanNew("DEADLINE"), DEADLINE); - Handle CENSUS_STATS_CONTEXT( - NanNew(GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)); - propagate->Set(NanNew("CENSUS_STATS_CONTEXT"), CENSUS_STATS_CONTEXT); - Handle CENSUS_TRACING_CONTEXT( - NanNew(GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT)); - propagate->Set(NanNew("CENSUS_TRACING_CONTEXT"), CENSUS_TRACING_CONTEXT); - Handle CANCELLATION( - NanNew(GRPC_PROPAGATE_CANCELLATION)); - propagate->Set(NanNew("CANCELLATION"), CANCELLATION); - Handle DEFAULTS(NanNew(GRPC_PROPAGATE_DEFAULTS)); - propagate->Set(NanNew("DEFAULTS"), DEFAULTS); +void InitPropagateConstants(Local exports) { + Nan::HandleScope scope; + Local propagate = Nan::New(); + Nan::Set(exports, Nan::New("propagate").ToLocalChecked(), propagate); + Local DEADLINE(Nan::New(GRPC_PROPAGATE_DEADLINE)); + Nan::Set(propagate, Nan::New("DEADLINE").ToLocalChecked(), DEADLINE); + Local CENSUS_STATS_CONTEXT( + Nan::New(GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)); + Nan::Set(propagate, Nan::New("CENSUS_STATS_CONTEXT").ToLocalChecked(), + CENSUS_STATS_CONTEXT); + Local CENSUS_TRACING_CONTEXT( + Nan::New(GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT)); + Nan::Set(propagate, Nan::New("CENSUS_TRACING_CONTEXT").ToLocalChecked(), + CENSUS_TRACING_CONTEXT); + Local CANCELLATION( + Nan::New(GRPC_PROPAGATE_CANCELLATION)); + Nan::Set(propagate, Nan::New("CANCELLATION").ToLocalChecked(), CANCELLATION); + Local DEFAULTS(Nan::New(GRPC_PROPAGATE_DEFAULTS)); + Nan::Set(propagate, Nan::New("DEFAULTS").ToLocalChecked(), DEFAULTS); } -void InitConnectivityStateConstants(Handle exports) { - NanScope(); - Handle channel_state = NanNew(); - exports->Set(NanNew("connectivityState"), channel_state); - Handle IDLE(NanNew(GRPC_CHANNEL_IDLE)); - channel_state->Set(NanNew("IDLE"), IDLE); - Handle CONNECTING(NanNew(GRPC_CHANNEL_CONNECTING)); - channel_state->Set(NanNew("CONNECTING"), CONNECTING); - Handle READY(NanNew(GRPC_CHANNEL_READY)); - channel_state->Set(NanNew("READY"), READY); - Handle TRANSIENT_FAILURE( - NanNew(GRPC_CHANNEL_TRANSIENT_FAILURE)); - channel_state->Set(NanNew("TRANSIENT_FAILURE"), TRANSIENT_FAILURE); - Handle FATAL_FAILURE( - NanNew(GRPC_CHANNEL_FATAL_FAILURE)); - channel_state->Set(NanNew("FATAL_FAILURE"), FATAL_FAILURE); +void InitConnectivityStateConstants(Local exports) { + Nan::HandleScope scope; + Local channel_state = Nan::New(); + Nan::Set(exports, Nan::New("connectivityState").ToLocalChecked(), + channel_state); + Local IDLE(Nan::New(GRPC_CHANNEL_IDLE)); + Nan::Set(channel_state, Nan::New("IDLE").ToLocalChecked(), IDLE); + Local CONNECTING(Nan::New(GRPC_CHANNEL_CONNECTING)); + Nan::Set(channel_state, Nan::New("CONNECTING").ToLocalChecked(), CONNECTING); + Local READY(Nan::New(GRPC_CHANNEL_READY)); + Nan::Set(channel_state, Nan::New("READY").ToLocalChecked(), READY); + Local TRANSIENT_FAILURE( + Nan::New(GRPC_CHANNEL_TRANSIENT_FAILURE)); + Nan::Set(channel_state, Nan::New("TRANSIENT_FAILURE").ToLocalChecked(), + TRANSIENT_FAILURE); + Local FATAL_FAILURE( + Nan::New(GRPC_CHANNEL_FATAL_FAILURE)); + Nan::Set(channel_state, Nan::New("FATAL_FAILURE").ToLocalChecked(), + FATAL_FAILURE); } -void InitWriteFlags(Handle exports) { - NanScope(); - Handle write_flags = NanNew(); - exports->Set(NanNew("writeFlags"), write_flags); - Handle BUFFER_HINT(NanNew(GRPC_WRITE_BUFFER_HINT)); - write_flags->Set(NanNew("BUFFER_HINT"), BUFFER_HINT); - Handle NO_COMPRESS(NanNew(GRPC_WRITE_NO_COMPRESS)); - write_flags->Set(NanNew("NO_COMPRESS"), NO_COMPRESS); +void InitWriteFlags(Local exports) { + Nan::HandleScope scope; + Local write_flags = Nan::New(); + Nan::Set(exports, Nan::New("writeFlags").ToLocalChecked(), write_flags); + Local BUFFER_HINT(Nan::New(GRPC_WRITE_BUFFER_HINT)); + Nan::Set(write_flags, Nan::New("BUFFER_HINT").ToLocalChecked(), BUFFER_HINT); + Local NO_COMPRESS(Nan::New(GRPC_WRITE_NO_COMPRESS)); + Nan::Set(write_flags, Nan::New("NO_COMPRESS").ToLocalChecked(), NO_COMPRESS); } -void init(Handle exports) { - NanScope(); +void init(Local exports) { + Nan::HandleScope scope; grpc_init(); InitStatusConstants(exports); InitCallErrorConstants(exports); diff --git a/src/node/ext/server.cc b/src/node/ext/server.cc index 32a8ff55b12..87363fc446b 100644 --- a/src/node/ext/server.cc +++ b/src/node/ext/server.cc @@ -50,6 +50,15 @@ namespace grpc { namespace node { +using Nan::Callback; +using Nan::EscapableHandleScope; +using Nan::HandleScope; +using Nan::Maybe; +using Nan::MaybeLocal; +using Nan::ObjectWrap; +using Nan::Persistent; +using Nan::Utf8String; + using std::unique_ptr; using v8::Array; using v8::Boolean; @@ -57,16 +66,13 @@ using v8::Date; using v8::Exception; using v8::Function; using v8::FunctionTemplate; -using v8::Handle; -using v8::HandleScope; using v8::Local; using v8::Number; using v8::Object; -using v8::Persistent; using v8::String; using v8::Value; -NanCallback *Server::constructor; +Nan::Callback *Server::constructor; Persistent Server::fun_tpl; class NewCallOp : public Op { @@ -82,22 +88,26 @@ class NewCallOp : public Op { grpc_metadata_array_destroy(&request_metadata); } - Handle GetNodeValue() const { - NanEscapableScope(); + Local GetNodeValue() const { + Nan::EscapableHandleScope scope; if (call == NULL) { - return NanEscapeScope(NanNull()); + return scope.Escape(Nan::Null()); } - Handle obj = NanNew(); - obj->Set(NanNew("call"), Call::WrapStruct(call)); - obj->Set(NanNew("method"), NanNew(details.method)); - obj->Set(NanNew("host"), NanNew(details.host)); - obj->Set(NanNew("deadline"), - NanNew(TimespecToMilliseconds(details.deadline))); - obj->Set(NanNew("metadata"), ParseMetadata(&request_metadata)); - return NanEscapeScope(obj); + Local obj = Nan::New(); + Nan::Set(obj, Nan::New("call").ToLocalChecked(), Call::WrapStruct(call)); + Nan::Set(obj, Nan::New("method").ToLocalChecked(), + Nan::New(details.method).ToLocalChecked()); + Nan::Set(obj, Nan::New("host").ToLocalChecked(), + Nan::New(details.host).ToLocalChecked()); + Nan::Set(obj, Nan::New("deadline").ToLocalChecked(), + Nan::New( + TimespecToMilliseconds(details.deadline)).ToLocalChecked()); + Nan::Set(obj, Nan::New("metadata").ToLocalChecked(), + ParseMetadata(&request_metadata)); + return scope.Escape(obj); } - bool ParseOp(Handle value, grpc_op *out, + bool ParseOp(Local value, grpc_op *out, shared_ptr resources) { return true; } @@ -124,35 +134,25 @@ Server::~Server() { grpc_completion_queue_destroy(this->shutdown_queue); } -void Server::Init(Handle exports) { - NanScope(); - Local tpl = NanNew(New); - tpl->SetClassName(NanNew("Server")); +void Server::Init(Local exports) { + HandleScope scope; + Local tpl = Nan::New(New); + tpl->SetClassName(Nan::New("Server").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); - NanSetPrototypeTemplate(tpl, "requestCall", - NanNew(RequestCall)->GetFunction()); - - NanSetPrototypeTemplate( - tpl, "addHttp2Port", - NanNew(AddHttp2Port)->GetFunction()); - - NanSetPrototypeTemplate(tpl, "start", - NanNew(Start)->GetFunction()); - - NanSetPrototypeTemplate(tpl, "tryShutdown", - NanNew(TryShutdown)->GetFunction()); - NanSetPrototypeTemplate( - tpl, "forceShutdown", - NanNew(ForceShutdown)->GetFunction()); - - NanAssignPersistent(fun_tpl, tpl); - Handle ctr = tpl->GetFunction(); - constructor = new NanCallback(ctr); - exports->Set(NanNew("Server"), ctr); + Nan::SetPrototypeMethod(tpl, "requestCall", RequestCall); + Nan::SetPrototypeMethod(tpl, "addHttp2Port", AddHttp2Port); + Nan::SetPrototypeMethod(tpl, "start", Start); + Nan::SetPrototypeMethod(tpl, "tryShutdown", TryShutdown); + Nan::SetPrototypeMethod(tpl, "forceShutdown", ForceShutdown); + fun_tpl.Reset(tpl); + Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); + Nan::Set(exports, Nan::New("Server").ToLocalChecked(), ctr); + constructor = new Callback(ctr); } -bool Server::HasInstance(Handle val) { - return NanHasInstance(fun_tpl, val); +bool Server::HasInstance(Local val) { + HandleScope scope; + return Nan::New(fun_tpl)->HasInstance(val); } void Server::ShutdownServer() { @@ -165,64 +165,77 @@ void Server::ShutdownServer() { } NAN_METHOD(Server::New) { - NanScope(); - /* If this is not a constructor call, make a constructor call and return the result */ - if (!args.IsConstructCall()) { + if (!info.IsConstructCall()) { const int argc = 1; - Local argv[argc] = {args[0]}; - NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = {info[0]}; + MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance( + argc, argv); + if (maybe_instance.IsEmpty()) { + // There's probably a pending exception + return; + } else { + info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); + return; + } } grpc_server *wrapped_server; grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue(); - if (args[0]->IsUndefined()) { + if (info[0]->IsUndefined()) { wrapped_server = grpc_server_create(NULL, NULL); - } else if (args[0]->IsObject()) { - Handle args_hash(args[0]->ToObject()); - Handle keys(args_hash->GetOwnPropertyNames()); + } else if (info[0]->IsObject()) { + Local args_hash = Nan::To(info[0]).ToLocalChecked(); + Local keys = Nan::GetOwnPropertyNames(args_hash).ToLocalChecked(); grpc_channel_args channel_args; channel_args.num_args = keys->Length(); channel_args.args = reinterpret_cast( calloc(channel_args.num_args, sizeof(grpc_arg))); /* These are used to keep all strings until then end of the block, then destroy them */ - std::vector key_strings(keys->Length()); - std::vector value_strings(keys->Length()); + std::vector key_strings(keys->Length()); + std::vector value_strings(keys->Length()); for (unsigned int i = 0; i < channel_args.num_args; i++) { - Handle current_key(keys->Get(i)->ToString()); - Handle current_value(args_hash->Get(current_key)); - key_strings[i] = new NanUtf8String(current_key); + MaybeLocal maybe_key = Nan::To( + Nan::Get(keys, i).ToLocalChecked()); + if (maybe_key.IsEmpty()) { + free(channel_args.args); + return Nan::ThrowTypeError("Arg keys must be strings"); + } + Local current_key = maybe_key.ToLocalChecked(); + Local current_value = Nan::Get(args_hash, + current_key).ToLocalChecked(); + key_strings[i] = new Utf8String(current_key); channel_args.args[i].key = **key_strings[i]; if (current_value->IsInt32()) { channel_args.args[i].type = GRPC_ARG_INTEGER; - channel_args.args[i].value.integer = current_value->Int32Value(); + channel_args.args[i].value.integer = Nan::To( + current_value).FromJust(); } else if (current_value->IsString()) { channel_args.args[i].type = GRPC_ARG_STRING; - value_strings[i] = new NanUtf8String(current_value); + value_strings[i] = new Utf8String(current_value); channel_args.args[i].value.string = **value_strings[i]; } else { free(channel_args.args); - return NanThrowTypeError("Arg values must be strings"); + return Nan::ThrowTypeError("Arg values must be strings"); } } wrapped_server = grpc_server_create(&channel_args, NULL); free(channel_args.args); } else { - return NanThrowTypeError("Server expects an object"); + return Nan::ThrowTypeError("Server expects an object"); } grpc_server_register_completion_queue(wrapped_server, queue, NULL); Server *server = new Server(wrapped_server); - server->Wrap(args.This()); - NanReturnValue(args.This()); + server->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); } NAN_METHOD(Server::RequestCall) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("requestCall can only be called on a Server"); + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("requestCall can only be called on a Server"); } - Server *server = ObjectWrap::Unwrap(args.This()); + Server *server = ObjectWrap::Unwrap(info.This()); NewCallOp *op = new NewCallOp(); unique_ptr ops(new OpVec()); ops->push_back(unique_ptr(op)); @@ -230,79 +243,74 @@ NAN_METHOD(Server::RequestCall) { server->wrapped_server, &op->call, &op->details, &op->request_metadata, CompletionQueueAsyncWorker::GetQueue(), CompletionQueueAsyncWorker::GetQueue(), - new struct tag(new NanCallback(args[0].As()), ops.release(), + new struct tag(new Callback(info[0].As()), ops.release(), shared_ptr(nullptr))); if (error != GRPC_CALL_OK) { - return NanThrowError(nanErrorWithCode("requestCall failed", error)); + return Nan::ThrowError(nanErrorWithCode("requestCall failed", error)); } CompletionQueueAsyncWorker::Next(); - NanReturnUndefined(); } NAN_METHOD(Server::AddHttp2Port) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError( + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError( "addHttp2Port can only be called on a Server"); } - if (!args[0]->IsString()) { - return NanThrowTypeError( + if (!info[0]->IsString()) { + return Nan::ThrowTypeError( "addHttp2Port's first argument must be a String"); } - if (!ServerCredentials::HasInstance(args[1])) { - return NanThrowTypeError( + if (!ServerCredentials::HasInstance(info[1])) { + return Nan::ThrowTypeError( "addHttp2Port's second argument must be ServerCredentials"); } - Server *server = ObjectWrap::Unwrap(args.This()); + Server *server = ObjectWrap::Unwrap(info.This()); ServerCredentials *creds_object = ObjectWrap::Unwrap( - args[1]->ToObject()); + Nan::To(info[1]).ToLocalChecked()); grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials(); int port; if (creds == NULL) { port = grpc_server_add_insecure_http2_port(server->wrapped_server, - *NanUtf8String(args[0])); + *Utf8String(info[0])); } else { port = grpc_server_add_secure_http2_port(server->wrapped_server, - *NanUtf8String(args[0]), + *Utf8String(info[0]), creds); } - NanReturnValue(NanNew(port)); + info.GetReturnValue().Set(Nan::New(port)); } NAN_METHOD(Server::Start) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("start can only be called on a Server"); + Nan::HandleScope scope; + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("start can only be called on a Server"); } - Server *server = ObjectWrap::Unwrap(args.This()); + Server *server = ObjectWrap::Unwrap(info.This()); grpc_server_start(server->wrapped_server); - NanReturnUndefined(); } NAN_METHOD(Server::TryShutdown) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("tryShutdown can only be called on a Server"); + Nan::HandleScope scope; + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("tryShutdown can only be called on a Server"); } - Server *server = ObjectWrap::Unwrap(args.This()); + Server *server = ObjectWrap::Unwrap(info.This()); unique_ptr ops(new OpVec()); grpc_server_shutdown_and_notify( server->wrapped_server, CompletionQueueAsyncWorker::GetQueue(), - new struct tag(new NanCallback(args[0].As()), ops.release(), + new struct tag(new Nan::Callback(info[0].As()), ops.release(), shared_ptr(nullptr))); CompletionQueueAsyncWorker::Next(); - NanReturnUndefined(); } NAN_METHOD(Server::ForceShutdown) { - NanScope(); - if (!HasInstance(args.This())) { - return NanThrowTypeError("forceShutdown can only be called on a Server"); + Nan::HandleScope scope; + if (!HasInstance(info.This())) { + return Nan::ThrowTypeError("forceShutdown can only be called on a Server"); } - Server *server = ObjectWrap::Unwrap(args.This()); + Server *server = ObjectWrap::Unwrap(info.This()); server->ShutdownServer(); - NanReturnUndefined(); } } // namespace node diff --git a/src/node/ext/server.h b/src/node/ext/server.h index e7d5c3fb11a..ab5fc210e8a 100644 --- a/src/node/ext/server.h +++ b/src/node/ext/server.h @@ -44,14 +44,14 @@ namespace node { /* Wraps grpc_server as a JavaScript object. Provides a constructor and wrapper methods for grpc_server_create, grpc_server_request_call, grpc_server_add_http2_port, and grpc_server_start. */ -class Server : public ::node::ObjectWrap { +class Server : public Nan::ObjectWrap { public: /* Initializes the Server class and exposes the constructor and wrapper methods to JavaScript */ - static void Init(v8::Handle exports); + static void Init(v8::Local exports); /* Tests whether the given value was constructed by this class's JavaScript constructor */ - static bool HasInstance(v8::Handle val); + static bool HasInstance(v8::Local val); private: explicit Server(grpc_server *server); @@ -69,8 +69,8 @@ class Server : public ::node::ObjectWrap { static NAN_METHOD(Start); static NAN_METHOD(TryShutdown); static NAN_METHOD(ForceShutdown); - static NanCallback *constructor; - static v8::Persistent fun_tpl; + static Nan::Callback *constructor; + static Nan::Persistent fun_tpl; grpc_server *wrapped_server; grpc_completion_queue *shutdown_queue; diff --git a/src/node/ext/server_credentials.cc b/src/node/ext/server_credentials.cc index b1201eb6641..5e922bd877d 100644 --- a/src/node/ext/server_credentials.cc +++ b/src/node/ext/server_credentials.cc @@ -41,22 +41,28 @@ namespace grpc { namespace node { +using Nan::Callback; +using Nan::EscapableHandleScope; +using Nan::HandleScope; +using Nan::Maybe; +using Nan::MaybeLocal; +using Nan::ObjectWrap; +using Nan::Persistent; +using Nan::Utf8String; + using v8::Array; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; -using v8::Handle; -using v8::HandleScope; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; -using v8::Persistent; using v8::String; using v8::Value; -NanCallback *ServerCredentials::constructor; +Nan::Callback *ServerCredentials::constructor; Persistent ServerCredentials::fun_tpl; ServerCredentials::ServerCredentials(grpc_server_credentials *credentials) @@ -66,33 +72,41 @@ ServerCredentials::~ServerCredentials() { grpc_server_credentials_release(wrapped_credentials); } -void ServerCredentials::Init(Handle exports) { - NanScope(); - Local tpl = NanNew(New); - tpl->SetClassName(NanNew("ServerCredentials")); +void ServerCredentials::Init(Local exports) { + Nan::HandleScope scope; + Local tpl = Nan::New(New); + tpl->SetClassName(Nan::New("ServerCredentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); - NanAssignPersistent(fun_tpl, tpl); - Handle ctr = tpl->GetFunction(); - ctr->Set(NanNew("createSsl"), - NanNew(CreateSsl)->GetFunction()); - ctr->Set(NanNew("createInsecure"), - NanNew(CreateInsecure)->GetFunction()); - constructor = new NanCallback(ctr); - exports->Set(NanNew("ServerCredentials"), ctr); + Local ctr = tpl->GetFunction(); + Nan::Set(ctr, Nan::New("createSsl").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateSsl)).ToLocalChecked()); + Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), + Nan::GetFunction( + Nan::New(CreateInsecure)).ToLocalChecked()); + fun_tpl.Reset(tpl); + constructor = new Nan::Callback(ctr); + Nan::Set(exports, Nan::New("ServerCredentials").ToLocalChecked(), ctr); } -bool ServerCredentials::HasInstance(Handle val) { - NanScope(); - return NanHasInstance(fun_tpl, val); +bool ServerCredentials::HasInstance(Local val) { + Nan::HandleScope scope; + return Nan::New(fun_tpl)->HasInstance(val); } -Handle ServerCredentials::WrapStruct( +Local ServerCredentials::WrapStruct( grpc_server_credentials *credentials) { - NanEscapableScope(); + Nan::EscapableHandleScope scope; const int argc = 1; - Handle argv[argc] = { - NanNew(reinterpret_cast(credentials))}; - return NanEscapeScope(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = { + Nan::New(reinterpret_cast(credentials))}; + MaybeLocal maybe_instance = Nan::NewInstance( + constructor->GetFunction(), argc, argv); + if (maybe_instance.IsEmpty()) { + return scope.Escape(Nan::Null()); + } else { + return scope.Escape(maybe_instance.ToLocalChecked()); + } } grpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() { @@ -100,96 +114,103 @@ grpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() { } NAN_METHOD(ServerCredentials::New) { - NanScope(); - - if (args.IsConstructCall()) { - if (!args[0]->IsExternal()) { - return NanThrowTypeError( + if (info.IsConstructCall()) { + if (!info[0]->IsExternal()) { + return Nan::ThrowTypeError( "ServerCredentials can only be created with the provide functions"); } - Handle ext = args[0].As(); + Local ext = info[0].As(); grpc_server_credentials *creds_value = reinterpret_cast(ext->Value()); ServerCredentials *credentials = new ServerCredentials(creds_value); - credentials->Wrap(args.This()); - NanReturnValue(args.This()); + credentials->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); } else { const int argc = 1; - Local argv[argc] = {args[0]}; - NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv)); + Local argv[argc] = {info[0]}; + MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance( + argc, argv); + if (maybe_instance.IsEmpty()) { + // There's probably a pending exception + return; + } else { + info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); + } } } NAN_METHOD(ServerCredentials::CreateSsl) { - // TODO: have the node API support multiple key/cert pairs. - NanScope(); + Nan::HandleScope scope; char *root_certs = NULL; - if (::node::Buffer::HasInstance(args[0])) { - root_certs = ::node::Buffer::Data(args[0]); - } else if (!(args[0]->IsNull() || args[0]->IsUndefined())) { - return NanThrowTypeError( + if (::node::Buffer::HasInstance(info[0])) { + root_certs = ::node::Buffer::Data(info[0]); + } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { + return Nan::ThrowTypeError( "createSSl's first argument must be a Buffer if provided"); } - if (!args[1]->IsArray()) { - return NanThrowTypeError( + if (!info[1]->IsArray()) { + return Nan::ThrowTypeError( "createSsl's second argument must be a list of objects"); } int force_client_auth = 0; - if (args[2]->IsBoolean()) { - force_client_auth = (int)args[2]->BooleanValue(); - } else if (!(args[2]->IsUndefined() || args[2]->IsNull())) { - return NanThrowTypeError( + if (info[2]->IsBoolean()) { + force_client_auth = (int)Nan::To(info[2]).FromJust(); + } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) { + return Nan::ThrowTypeError( "createSsl's third argument must be a boolean if provided"); } - Handle pair_list = Local::Cast(args[1]); + Local pair_list = Local::Cast(info[1]); uint32_t key_cert_pair_count = pair_list->Length(); grpc_ssl_pem_key_cert_pair *key_cert_pairs = new grpc_ssl_pem_key_cert_pair[ key_cert_pair_count]; - Handle key_key = NanNew("private_key"); - Handle cert_key = NanNew("cert_chain"); + Local key_key = Nan::New("private_key").ToLocalChecked(); + Local cert_key = Nan::New("cert_chain").ToLocalChecked(); for(uint32_t i = 0; i < key_cert_pair_count; i++) { - if (!pair_list->Get(i)->IsObject()) { + Local pair_val = Nan::Get(pair_list, i).ToLocalChecked(); + if (!pair_val->IsObject()) { delete key_cert_pairs; - return NanThrowTypeError("Key/cert pairs must be objects"); + return Nan::ThrowTypeError("Key/cert pairs must be objects"); } - Handle pair_obj = pair_list->Get(i)->ToObject(); - if (!pair_obj->HasOwnProperty(key_key)) { + Local pair_obj = Nan::To(pair_val).ToLocalChecked(); + MaybeLocal maybe_key = Nan::Get(pair_obj, key_key); + if (maybe_key.IsEmpty()) { delete key_cert_pairs; - return NanThrowTypeError( + return Nan::ThrowTypeError( "Key/cert pairs must have a private_key and a cert_chain"); } - if (!pair_obj->HasOwnProperty(cert_key)) { + MaybeLocal maybe_cert = Nan::Get(pair_obj, cert_key); + if (maybe_cert.IsEmpty()) { delete key_cert_pairs; - return NanThrowTypeError( + return Nan::ThrowTypeError( "Key/cert pairs must have a private_key and a cert_chain"); } - if (!::node::Buffer::HasInstance(pair_obj->Get(key_key))) { + if (!::node::Buffer::HasInstance(maybe_key.ToLocalChecked())) { delete key_cert_pairs; - return NanThrowTypeError("private_key must be a Buffer"); + return Nan::ThrowTypeError("private_key must be a Buffer"); } - if (!::node::Buffer::HasInstance(pair_obj->Get(cert_key))) { + if (!::node::Buffer::HasInstance(maybe_cert.ToLocalChecked())) { delete key_cert_pairs; - return NanThrowTypeError("cert_chain must be a Buffer"); + return Nan::ThrowTypeError("cert_chain must be a Buffer"); } key_cert_pairs[i].private_key = ::node::Buffer::Data( - pair_obj->Get(key_key)); + maybe_key.ToLocalChecked()); key_cert_pairs[i].cert_chain = ::node::Buffer::Data( - pair_obj->Get(cert_key)); + maybe_cert.ToLocalChecked()); } grpc_server_credentials *creds = grpc_ssl_server_credentials_create( root_certs, key_cert_pairs, key_cert_pair_count, force_client_auth, NULL); delete key_cert_pairs; if (creds == NULL) { - NanReturnNull(); + info.GetReturnValue().SetNull(); + } else { + info.GetReturnValue().Set(WrapStruct(creds)); } - NanReturnValue(WrapStruct(creds)); } NAN_METHOD(ServerCredentials::CreateInsecure) { - NanScope(); - NanReturnValue(WrapStruct(NULL)); + info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node diff --git a/src/node/ext/server_credentials.h b/src/node/ext/server_credentials.h index 63903f663c6..bf279e481c6 100644 --- a/src/node/ext/server_credentials.h +++ b/src/node/ext/server_credentials.h @@ -43,12 +43,12 @@ namespace grpc { namespace node { /* Wrapper class for grpc_server_credentials structs */ -class ServerCredentials : public ::node::ObjectWrap { +class ServerCredentials : public Nan::ObjectWrap { public: - static void Init(v8::Handle exports); - static bool HasInstance(v8::Handle val); + static void Init(v8::Local exports); + static bool HasInstance(v8::Local val); /* Wrap a grpc_server_credentials struct in a javascript object */ - static v8::Handle WrapStruct(grpc_server_credentials *credentials); + static v8::Local WrapStruct(grpc_server_credentials *credentials); /* Returns the grpc_server_credentials struct that this object wraps */ grpc_server_credentials *GetWrappedServerCredentials(); @@ -64,9 +64,9 @@ class ServerCredentials : public ::node::ObjectWrap { static NAN_METHOD(New); static NAN_METHOD(CreateSsl); static NAN_METHOD(CreateInsecure); - static NanCallback *constructor; + static Nan::Callback *constructor; // Used for typechecking instances of this javascript class - static v8::Persistent fun_tpl; + static Nan::Persistent fun_tpl; grpc_server_credentials *wrapped_credentials; }; diff --git a/src/node/interop/test.proto b/src/node/interop/test.proto index d2c3f9befef..24e67497fa6 100644 --- a/src/node/interop/test.proto +++ b/src/node/interop/test.proto @@ -45,7 +45,6 @@ service TestService { rpc EmptyCall(grpc.testing.Empty) returns (grpc.testing.Empty); // One request followed by one response. - // TODO(Issue 527): Describe required server behavior. rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // One request followed by a sequence of responses (streamed download). diff --git a/src/node/package.json b/src/node/package.json index bb8987cc0d7..22f94757ce6 100644 --- a/src/node/package.json +++ b/src/node/package.json @@ -1,6 +1,6 @@ { "name": "grpc", - "version": "0.11.0", + "version": "0.11.1", "author": "Google Inc.", "description": "gRPC Library for Node", "homepage": "http://www.grpc.io/", @@ -27,7 +27,7 @@ "dependencies": { "bindings": "^1.2.0", "lodash": "^3.9.3", - "nan": "^1.5.0", + "nan": "^2.0.0", "protobufjs": "^4.0.0" }, "devDependencies": { diff --git a/src/node/src/server.js b/src/node/src/server.js index b6f162adf85..70b4a9d80e3 100644 --- a/src/node/src/server.js +++ b/src/node/src/server.js @@ -276,6 +276,7 @@ function ServerWritableStream(call, serialize) { function _write(chunk, encoding, callback) { /* jshint validthis: true */ var batch = {}; + var self = this; if (!this.call.metadataSent) { batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); @@ -290,7 +291,7 @@ function _write(chunk, encoding, callback) { batch[grpc.opType.SEND_MESSAGE] = message; this.call.startBatch(batch, function(err, value) { if (err) { - this.emit('error', err); + self.emit('error', err); return; } callback(); @@ -305,6 +306,7 @@ ServerWritableStream.prototype._write = _write; */ function sendMetadata(responseMetadata) { /* jshint validthis: true */ + var self = this; if (!this.call.metadataSent) { this.call.metadataSent = true; var batch = []; @@ -312,7 +314,7 @@ function sendMetadata(responseMetadata) { responseMetadata._getCoreRepresentation(); this.call.startBatch(batch, function(err) { if (err) { - this.emit('error', err); + self.emit('error', err); return; } }); diff --git a/src/objective-c/GRPCClient/private/GRPCRequestHeaders.h b/src/objective-c/GRPCClient/private/GRPCRequestHeaders.h index ed08ae5f3c8..cf5a1be9d6a 100644 --- a/src/objective-c/GRPCClient/private/GRPCRequestHeaders.h +++ b/src/objective-c/GRPCClient/private/GRPCRequestHeaders.h @@ -34,7 +34,7 @@ #import #include -@class GRPCCall.h; +#import "../GRPCCall.h" @interface GRPCRequestHeaders : NSObject diff --git a/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m b/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m index 761677ce501..d23f21c0f9c 100644 --- a/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m +++ b/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m @@ -35,7 +35,6 @@ #import -#import "../GRPCCall.h" #import "NSDictionary+GRPC.h" // Used by the setter. diff --git a/src/objective-c/examples/RemoteTestClient/test.proto b/src/objective-c/examples/RemoteTestClient/test.proto index 2f5a5489b3d..514c3b80955 100644 --- a/src/objective-c/examples/RemoteTestClient/test.proto +++ b/src/objective-c/examples/RemoteTestClient/test.proto @@ -45,7 +45,6 @@ service TestService { rpc EmptyCall(grpc.testing.Empty) returns (grpc.testing.Empty); // One request followed by one response. - // TODO(Issue 527): Describe required server behavior. rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // One request followed by a sequence of responses (streamed download). diff --git a/src/objective-c/generated_libraries/RemoteTestClient/test.proto b/src/objective-c/generated_libraries/RemoteTestClient/test.proto index 2f5a5489b3d..514c3b80955 100644 --- a/src/objective-c/generated_libraries/RemoteTestClient/test.proto +++ b/src/objective-c/generated_libraries/RemoteTestClient/test.proto @@ -45,7 +45,6 @@ service TestService { rpc EmptyCall(grpc.testing.Empty) returns (grpc.testing.Empty); // One request followed by one response. - // TODO(Issue 527): Describe required server behavior. rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // One request followed by a sequence of responses (streamed download). diff --git a/src/php/README.md b/src/php/README.md index 51322c75269..a054258782d 100644 --- a/src/php/README.md +++ b/src/php/README.md @@ -5,7 +5,7 @@ This directory contains source code for PHP implementation of gRPC layered on sh #Status -Alpha : Ready for early adopters +Beta ## Environment @@ -49,7 +49,7 @@ sudo apt-get install libgrpc-dev Install the gRPC PHP extension ```sh -sudo pecl install grpc-alpha +sudo pecl install grpc-beta ``` **Mac OS X:** @@ -96,7 +96,7 @@ $ sudo make install # 'make' should have been run by core grpc Install the gRPC PHP extension ```sh -$ sudo pecl install grpc-alpha +$ sudo pecl install grpc-beta ``` OR @@ -109,15 +109,19 @@ $ make $ sudo make install ``` -In your php.ini file, add the line `extension=grpc.so` to load the extension -at PHP startup. +Add this line to your `php.ini` file, e.g. `/etc/php5/cli/php.ini` + +```sh +extension=grpc.so +``` Install Composer ```sh $ cd grpc/src/php $ curl -sS https://getcomposer.org/installer | php -$ php composer.phar install +$ sudo mv composer.phar /usr/local/bin/composer +$ composer install ``` ## Unit Tests @@ -164,6 +168,132 @@ $ cd grpc/src/php $ ./bin/run_gen_code_test.sh ``` +## Use the gRPC PHP extension with Apache + +Install `apache2`, in addition to `php5` above + +```sh +$ sudo apt-get install apache2 +``` + +Add this line to your `php.ini` file, e.g. `/etc/php5/apache2/php.ini` + +```sh +extension=grpc.so +``` + +Restart apache + +```sh +$ sudo service apache2 restart +``` + +Make sure the Node math server is still running, as above. + +```sh +$ cd grpc/src/node +$ nodejs examples/math_server.js +``` + +Make sure you have run `composer install` to generate the `vendor/autoload.php` file + +```sh +$ composer install +``` + +Make sure you have generated the client stub `math.php` + +```sh +$ ./bin/generate_proto_php.sh +``` + +Copy the `math_client.php` file into your Apache document root, e.g. + +```sh +$ cp tests/generated_code/math_client.php /var/www/html +``` + +You may have to fix the first two lines to point the includes to your installation: + +```php +include 'vendor/autoload.php'; +include 'tests/generated_code/math.php'; +``` + +Connect to `localhost/math_client.php` in your browser, or run this from command line: + +```sh +$ curl localhost/math_client.php +``` + +## Use the gRPC PHP extension with Nginx/PHP-FPM + +Install `nginx` and `php5-fpm`, in addition to `php5` above + +```sh +$ sudo apt-get install nginx php5-fpm +``` + +Add this line to your `php.ini` file, e.g. `/etc/php5/fpm/php.ini` + +```sh +extension=grpc.so +``` + +Uncomment the following lines in your `/etc/nginx/sites-available/default` file: + +``` +location ~ \.php$ { + include snippets/fastcgi-php.conf; + fastcgi_pass unix:/var/run/php5-fpm.sock; +} +``` + +Restart nginx and php-fpm + +```sh +$ sudo service nginx restart +$ sudo service php5-fpm restart +``` + +Make sure the Node math server is still running, as above. + +```sh +$ cd grpc/src/node +$ nodejs examples/math_server.js +``` + +Make sure you have run `composer install` to generate the `vendor/autoload.php` file + +```sh +$ composer install +``` + +Make sure you have generated the client stub `math.php` + +```sh +$ ./bin/generate_proto_php.sh +``` + +Copy the `math_client.php` file into your Nginx document root, e.g. + +```sh +$ cp tests/generated_code/math_client.php /var/www/html +``` + +You may have to fix the first two lines to point the includes to your installation: + +```php +include 'vendor/autoload.php'; +include 'tests/generated_code/math.php'; +``` + +Connect to `localhost/math_client.php` in your browser, or run this from command line: + +```sh +$ curl localhost/math_client.php +``` + [homebrew]:http://brew.sh [gRPC install script]:https://raw.githubusercontent.com/grpc/homebrew-grpc/master/scripts/install [Node]:https://github.com/grpc/grpc/tree/master/src/node/examples diff --git a/src/php/bin/run_tests.sh b/src/php/bin/run_tests.sh index 953f408ea8d..1fe68cdab4b 100755 --- a/src/php/bin/run_tests.sh +++ b/src/php/bin/run_tests.sh @@ -31,7 +31,11 @@ # Loads the local shared library, and runs all of the test cases in tests/ # against it set -e -cd $(dirname $0) +cd $(dirname $0)/../../.. +root=$(pwd) +cd src/php/bin source ./determine_extension_dir.sh +# in some jenkins macos machine, somehow the PHP build script can't find libgrpc.dylib +export DYLD_LIBRARY_PATH=$root/libs/$config php $extension_dir $(which phpunit) -v --debug --strict \ ../tests/unit_tests diff --git a/src/php/tests/generated_code/math_client.php b/src/php/tests/generated_code/math_client.php new file mode 100644 index 00000000000..7bc78287be8 --- /dev/null +++ b/src/php/tests/generated_code/math_client.php @@ -0,0 +1,102 @@ +\n"); +} + +$host = "localhost:50051"; +p("Connecting to host: $host"); +$client = new math\MathClient($host, []); +p("Client class: ".get_class($client)); +p(''); + +p("Running unary call test:"); +$dividend = 7; +$divisor = 4; +$div_arg = new math\DivArgs(); +$div_arg->setDividend($dividend); +$div_arg->setDivisor($divisor); +$call = $client->Div($div_arg); +p("Call peer: ".$call->getPeer()); +p("Dividing $dividend by $divisor"); +list($response, $status) = $call->wait(); +p("quotient = ".$response->getQuotient()); +p("remainder = ".$response->getRemainder()); +p(''); + +p("Running server streaming test:"); +$limit = 7; +$fib_arg = new math\FibArgs(); +$fib_arg->setLimit($limit); +$call = $client->Fib($fib_arg); +$result_array = iterator_to_array($call->responses()); +$result = ''; +foreach ($result_array as $num) { + $result .= ' '.$num->getNum(); +} +p("The first $limit Fibonacci numbers are:".$result); +p(''); + +p("Running client streaming test:"); +$call = $client->Sum(); +for ($i = 0; $i <= $limit; $i++) { + $num = new math\Num(); + $num->setNum($i); + $call->write($num); +} +list($response, $status) = $call->wait(); +p(sprintf("The first %d positive integers sum to: %d", + $limit, $response->getNum())); +p(''); + +p("Running bidi-streaming test:"); +$call = $client->DivMany(); +for ($i = 0; $i < 7; $i++) { + $div_arg = new math\DivArgs(); + $dividend = 2 * $i + 1; + $divisor = 3; + $div_arg->setDividend($dividend); + $div_arg->setDivisor($divisor); + $call->write($div_arg); + p("client writing: $dividend / $divisor"); + $response = $call->read(); + p(sprintf("server writing: quotient = %d, remainder = %d", + $response->getQuotient(), $response->getRemainder())); +} +$call->writesDone(); diff --git a/src/php/tests/interop/test.proto b/src/php/tests/interop/test.proto index 39c08f3544a..0d169e7f640 100644 --- a/src/php/tests/interop/test.proto +++ b/src/php/tests/interop/test.proto @@ -44,7 +44,6 @@ service TestService { rpc EmptyCall(grpc.testing.EmptyMessage) returns (grpc.testing.EmptyMessage); // One request followed by one response. - // TODO(Issue 527): Describe required server behavior. rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // One request followed by a sequence of responses (streamed download). diff --git a/src/php/tests/unit_tests/EndToEndTest.php b/src/php/tests/unit_tests/EndToEndTest.php index bd464f939fc..b65366233ad 100755 --- a/src/php/tests/unit_tests/EndToEndTest.php +++ b/src/php/tests/unit_tests/EndToEndTest.php @@ -204,11 +204,11 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{ } public function testWatchConnectivityStateFailed() { - $idle_state = $this->channel->getConnectivityState(true); + $idle_state = $this->channel->getConnectivityState(); $this->assertTrue($idle_state == Grpc\CHANNEL_IDLE); $now = Grpc\Timeval::now(); - $delta = new Grpc\Timeval(1); + $delta = new Grpc\Timeval(500000); // should timeout $deadline = $now->add($delta); $this->assertFalse($this->channel->watchConnectivityState( diff --git a/src/python/grpcio/grpc/beta/implementations.py b/src/python/grpcio/grpc/beta/implementations.py index 9b461fb3ddf..c9d64ad35a0 100644 --- a/src/python/grpcio/grpc/beta/implementations.py +++ b/src/python/grpcio/grpc/beta/implementations.py @@ -147,7 +147,7 @@ def secure_channel(host, port, client_credentials): A secure Channel to the remote host through which RPCs may be conducted. """ intermediary_low_channel = _intermediary_low.Channel( - '%s:%d' % (host, port), client_credentials.intermediary_low_credentials) + '%s:%d' % (host, port), client_credentials._intermediary_low_credentials) return Channel(intermediary_low_channel._internal, intermediary_low_channel) # pylint: disable=protected-access diff --git a/src/python/grpcio/requirements.txt b/src/python/grpcio/requirements.txt index 608ba402e09..77356e0a747 100644 --- a/src/python/grpcio/requirements.txt +++ b/src/python/grpcio/requirements.txt @@ -1,2 +1,2 @@ -enum34==1.0.4 -futures==2.2.0 +enum34>=1.0.4 +futures>=2.2.0 diff --git a/src/python/grpcio/setup.py b/src/python/grpcio/setup.py index 151b2bfcb4d..8b87c09d5c2 100644 --- a/src/python/grpcio/setup.py +++ b/src/python/grpcio/setup.py @@ -87,9 +87,8 @@ _PACKAGE_DIRECTORIES = { } _INSTALL_REQUIRES = ( - 'enum34==1.0.4', - 'futures==2.2.0', - 'protobuf==3.0.0a3', + 'enum34>=1.0.4', + 'futures>=2.2.0', ) _SETUP_REQUIRES = ( @@ -104,7 +103,7 @@ _COMMAND_CLASS = { setuptools.setup( name='grpcio', - version='0.11.0b0', + version='0.11.0b1', ext_modules=_EXTENSION_MODULES, packages=list(_PACKAGES), package_dir=_PACKAGE_DIRECTORIES, diff --git a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py index 272a37f15f8..30327369755 100644 --- a/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py +++ b/src/python/grpcio_test/grpc_test/framework/interfaces/face/_future_invocation_asynchronous_event_service.py @@ -72,6 +72,36 @@ class _PauseableIterator(object): return next(self._upstream) +class _Callback(object): + + def __init__(self): + self._condition = threading.Condition() + self._called = False + self._passed_future = None + self._passed_other_stuff = None + + def __call__(self, *args, **kwargs): + with self._condition: + self._called = True + if args: + self._passed_future = args[0] + if 1 < len(args) or kwargs: + self._passed_other_stuff = tuple(args[1:]), dict(kwargs) + self._condition.notify_all() + + def future(self): + with self._condition: + while True: + if self._passed_other_stuff is not None: + raise ValueError( + 'Test callback passed unexpected values: %s', + self._passed_other_stuff) + elif self._called: + return self._passed_future + else: + self._condition.wait() + + class TestCase(test_coverage.Coverage, unittest.TestCase): """A test of the Face layer of RPC Framework. @@ -112,12 +142,15 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() + callback = _Callback() response_future = self._invoker.future(group, method)( request, test_constants.LONG_TIMEOUT) + response_future.add_done_callback(callback) response = response_future.result() test_messages.verify(request, response, self) + self.assertIs(callback.future(), response_future) def testSuccessfulUnaryRequestStreamResponse(self): for (group, method), test_messages_sequence in ( @@ -137,15 +170,19 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): for test_messages in test_messages_sequence: requests = test_messages.requests() request_iterator = _PauseableIterator(iter(requests)) + callback = _Callback() # Use of a paused iterator of requests allows us to test that control is # returned to calling code before the iterator yields any requests. with request_iterator.pause(): response_future = self._invoker.future(group, method)( request_iterator, test_constants.LONG_TIMEOUT) - response = response_future.result() + response_future.add_done_callback(callback) + future_passed_to_callback = callback.future() + response = future_passed_to_callback.result() test_messages.verify(requests, response, self) + self.assertIs(future_passed_to_callback, response_future) def testSuccessfulStreamRequestStreamResponse(self): for (group, method), test_messages_sequence in ( @@ -208,12 +245,15 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() + callback = _Callback() with self._control.pause(): response_future = self._invoker.future(group, method)( request, test_constants.LONG_TIMEOUT) + response_future.add_done_callback(callback) cancel_method_return_value = response_future.cancel() + self.assertIs(callback.future(), response_future) self.assertFalse(cancel_method_return_value) self.assertTrue(response_future.cancelled()) @@ -236,12 +276,15 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): self._digest.stream_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() + callback = _Callback() with self._control.pause(): response_future = self._invoker.future(group, method)( iter(requests), test_constants.LONG_TIMEOUT) + response_future.add_done_callback(callback) cancel_method_return_value = response_future.cancel() + self.assertIs(callback.future(), response_future) self.assertFalse(cancel_method_return_value) self.assertTrue(response_future.cancelled()) @@ -264,10 +307,13 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() + callback = _Callback() with self._control.pause(): response_future = self._invoker.future( group, method)(request, _3069_test_constant.REALLY_SHORT_TIMEOUT) + response_future.add_done_callback(callback) + self.assertIs(callback.future(), response_future) self.assertIsInstance( response_future.exception(), face.ExpirationError) with self.assertRaises(face.ExpirationError): @@ -290,10 +336,13 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): self._digest.stream_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() + callback = _Callback() with self._control.pause(): response_future = self._invoker.future(group, method)( iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT) + response_future.add_done_callback(callback) + self.assertIs(callback.future(), response_future) self.assertIsInstance( response_future.exception(), face.ExpirationError) with self.assertRaises(face.ExpirationError): @@ -316,11 +365,14 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() + callback = _Callback() with self._control.fail(): response_future = self._invoker.future(group, method)( request, _3069_test_constant.REALLY_SHORT_TIMEOUT) + response_future.add_done_callback(callback) + self.assertIs(callback.future(), response_future) # Because the servicer fails outside of the thread from which the # servicer-side runtime called into it its failure is # indistinguishable from simply not having called its @@ -350,11 +402,14 @@ class TestCase(test_coverage.Coverage, unittest.TestCase): self._digest.stream_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() + callback = _Callback() with self._control.fail(): response_future = self._invoker.future(group, method)( iter(requests), _3069_test_constant.REALLY_SHORT_TIMEOUT) + response_future.add_done_callback(callback) + self.assertIs(callback.future(), response_future) # Because the servicer fails outside of the thread from which the # servicer-side runtime called into it its failure is # indistinguishable from simply not having called its diff --git a/src/python/grpcio_test/setup.py b/src/python/grpcio_test/setup.py index 216119f0e7b..fe36bc9232b 100644 --- a/src/python/grpcio_test/setup.py +++ b/src/python/grpcio_test/setup.py @@ -72,6 +72,8 @@ _SETUP_REQUIRES = ( _INSTALL_REQUIRES = ( 'oauth2client>=1.4.7', 'grpcio>=0.11.0b0', + # TODO(issue 3321): Unpin protobuf dependency. + 'protobuf==3.0.0a3', ) _COMMAND_CLASS = { diff --git a/templates/Makefile.template b/templates/Makefile.template index d8370ce2689..978e7e70451 100644 --- a/templates/Makefile.template +++ b/templates/Makefile.template @@ -65,8 +65,11 @@ endif + MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) ifndef BUILDDIR - BUILDDIR = . + BUILDDIR_ABSOLUTE = $(patsubst %/,%,$(dir $(MAKEFILE_PATH))) + else + BUILDDIR_ABSOLUTE = $(abspath $(BUILDDIR)) endif HAS_GCC = $(shell which gcc > /dev/null 2> /dev/null && echo true || echo false) @@ -92,10 +95,10 @@ endif - BINDIR = $(BUILDDIR)/bins - OBJDIR = $(BUILDDIR)/objs - LIBDIR = $(BUILDDIR)/libs - GENDIR = $(BUILDDIR)/gens + BINDIR = $(BUILDDIR_ABSOLUTE)/bins + OBJDIR = $(BUILDDIR_ABSOLUTE)/objs + LIBDIR = $(BUILDDIR_ABSOLUTE)/libs + GENDIR = $(BUILDDIR_ABSOLUTE)/gens # Configurations @@ -1599,13 +1602,13 @@ $(Q) $(AR) rcs $(LIBDIR)/$(CONFIG)/lib${lib.name}.a $(LIB${lib.name.upper()}_OBJS) % if lib.get('baselib', False): % if lib.get('secure', 'check') == True: - $(Q) rm -rf tmp-merge-${lib.name} - $(Q) mkdir tmp-merge-${lib.name} - $(Q) ( cd tmp-merge-${lib.name} ; $(AR) x ../$(LIBDIR)/$(CONFIG)/lib${lib.name}.a ) - $(Q) for l in $(OPENSSL_MERGE_LIBS) ; do ( cd tmp-merge-${lib.name} ; <%text>ar x ../$${l} ) ; done - $(Q) rm -f $(LIBDIR)/$(CONFIG)/lib${lib.name}.a tmp-merge-${lib.name}/__.SYMDEF* - $(Q) ar rcs $(LIBDIR)/$(CONFIG)/lib${lib.name}.a tmp-merge-${lib.name}/* - $(Q) rm -rf tmp-merge-${lib.name} + $(Q) rm -rf $(BUILDDIR_ABSOLUTE)/tmp-merge-${lib.name} + $(Q) mkdir $(BUILDDIR_ABSOLUTE)/tmp-merge-${lib.name} + $(Q) ( cd $(BUILDDIR_ABSOLUTE)/tmp-merge-${lib.name} ; $(AR) x $(LIBDIR)/$(CONFIG)/lib${lib.name}.a ) + $(Q) for l in $(OPENSSL_MERGE_LIBS) ; do ( cd $(BUILDDIR_ABSOLUTE)/tmp-merge-${lib.name} ; <%text>ar x $${l} ) ; done + $(Q) rm -f $(LIBDIR)/$(CONFIG)/lib${lib.name}.a $(BUILDDIR_ABSOLUTE)/tmp-merge-${lib.name}/__.SYMDEF* + $(Q) ar rcs $(LIBDIR)/$(CONFIG)/lib${lib.name}.a $(BUILDDIR_ABSOLUTE)/tmp-merge-${lib.name}/* + $(Q) rm -rf $(BUILDDIR_ABSOLUTE)/tmp-merge-${lib.name} % endif % endif ifeq ($(SYSTEM),Darwin) diff --git a/test/core/bad_client/gen_build_yaml.py b/test/core/bad_client/gen_build_yaml.py index 02dda10be0f..3df889ecdaf 100755 --- a/test/core/bad_client/gen_build_yaml.py +++ b/test/core/bad_client/gen_build_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/test/core/client_config/lb_policies_test.c b/test/core/client_config/lb_policies_test.c index 2960ba1db6e..b5f75dc3e85 100644 --- a/test/core/client_config/lb_policies_test.c +++ b/test/core/client_config/lb_policies_test.c @@ -609,26 +609,57 @@ static void verify_rebirth_round_robin(const servers_fixture *f, const int *actual_connection_sequence, const size_t num_iters) { int *expected_connection_sequence; - size_t i; + size_t i, j, unique_seq_last_idx, unique_seq_first_idx; const size_t expected_seq_length = f->num_servers; + uint8_t *seen_elements; /* verify conn. seq. expectation */ - /* get the first sequence of "num_servers" elements */ + /* get the first unique run of length "num_servers". */ expected_connection_sequence = gpr_malloc(sizeof(int) * expected_seq_length); - memcpy(expected_connection_sequence, actual_connection_sequence + 4, + seen_elements = gpr_malloc(sizeof(int) * expected_seq_length); + + unique_seq_last_idx = ~(size_t)0; + + memset(seen_elements, 0, sizeof(uint8_t) * expected_seq_length); + for (i = 0; i < num_iters; i++) { + if (actual_connection_sequence[i] < 0 || + seen_elements[actual_connection_sequence[i]] != 0) { + /* if anything breaks the uniqueness of the run, back to square zero */ + memset(seen_elements, 0, sizeof(uint8_t) * expected_seq_length); + continue; + } + seen_elements[actual_connection_sequence[i]] = 1; + for (j = 0; j < expected_seq_length; j++) { + if (seen_elements[j] == 0) break; + } + if (j == expected_seq_length) { /* seen all the elements */ + unique_seq_last_idx = i; + break; + } + } + /* make sure we found a valid run */ + for (j = 0; j < expected_seq_length; j++) { + GPR_ASSERT(seen_elements[j] != 0); + } + + GPR_ASSERT(unique_seq_last_idx != ~(size_t)0); + + unique_seq_first_idx = (unique_seq_last_idx - expected_seq_length + 1); + memcpy(expected_connection_sequence, + actual_connection_sequence + unique_seq_first_idx, sizeof(int) * expected_seq_length); /* first iteration succeeds */ GPR_ASSERT(actual_connection_sequence[0] != -1); + /* then we fail for a while... */ + GPR_ASSERT(actual_connection_sequence[1] == -1); + /* ... but should be up at "unique_seq_first_idx" */ + GPR_ASSERT(actual_connection_sequence[unique_seq_first_idx] != -1); - /* back up on the third (or maybe fourth) iteration */ - i = 3; - if (actual_connection_sequence[i] == -1) { - i = 4; - } - for (; i < num_iters; i++) { + for (j = 0, i = unique_seq_first_idx; i < num_iters; i++) { const int actual = actual_connection_sequence[i]; - const int expected = expected_connection_sequence[i % expected_seq_length]; + const int expected = + expected_connection_sequence[j++ % expected_seq_length]; if (actual != expected) { gpr_log(GPR_ERROR, "FAILURE: expected %d, actual %d at iter %d", expected, actual, i); @@ -642,6 +673,7 @@ static void verify_rebirth_round_robin(const servers_fixture *f, /* things are fine once the servers are brought back up */ assert_channel_connectivity(client, 1, GRPC_CHANNEL_READY); gpr_free(expected_connection_sequence); + gpr_free(seen_elements); } int main(int argc, char **argv) { diff --git a/test/core/end2end/gen_build_yaml.py b/test/core/end2end/gen_build_yaml.py index 46cdb80c863..9988950a6e5 100755 --- a/test/core/end2end/gen_build_yaml.py +++ b/test/core/end2end/gen_build_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/test/core/httpcli/test_server.py b/test/core/httpcli/test_server.py index babfe84ddca..4aaf5e30f8d 100755 --- a/test/core/httpcli/test_server.py +++ b/test/core/httpcli/test_server.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 """Server for httpcli_test""" diff --git a/test/proto/test.proto b/test/proto/test.proto index 92aff23929c..d3166a6540d 100644 --- a/test/proto/test.proto +++ b/test/proto/test.proto @@ -45,7 +45,6 @@ service TestService { rpc EmptyCall(grpc.testing.Empty) returns (grpc.testing.Empty); // One request followed by one response. - // TODO(Issue 527): Describe required server behavior. rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // One request followed by a sequence of responses (streamed download). diff --git a/third_party/protobuf b/third_party/protobuf index 23408684b4d..8fce8933649 160000 --- a/third_party/protobuf +++ b/third_party/protobuf @@ -1 +1 @@ -Subproject commit 23408684b4d2bf1b25e14314413a14d542c18bc4 +Subproject commit 8fce8933649ce09c1661ff2b5b7f6eb79badd251 diff --git a/tools/buildgen/build-cleaner.py b/tools/buildgen/build-cleaner.py index 939143c4cbc..6c9c6b3749e 100755 --- a/tools/buildgen/build-cleaner.py +++ b/tools/buildgen/build-cleaner.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/tools/buildgen/mako_renderer.py b/tools/buildgen/mako_renderer.py index abb8df2141a..f1b28d352e7 100755 --- a/tools/buildgen/mako_renderer.py +++ b/tools/buildgen/mako_renderer.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/tools/distrib/check_copyright.py b/tools/distrib/check_copyright.py index 1d09ed42a57..fac2a5af09c 100755 --- a/tools/distrib/check_copyright.py +++ b/tools/distrib/check_copyright.py @@ -1,4 +1,4 @@ -#!/usr/bin/python2.7 +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. diff --git a/tools/distrib/python/docgen.py b/tools/distrib/python/docgen.py index 2acd3cc12f2..4ac8f9c64a8 100755 --- a/tools/distrib/python/docgen.py +++ b/tools/distrib/python/docgen.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/tools/distrib/python/submit.py b/tools/distrib/python/submit.py index 909ba563270..dffbefd5fe4 100755 --- a/tools/distrib/python/submit.py +++ b/tools/distrib/python/submit.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/tools/dockerfile/grpc_python/Dockerfile b/tools/dockerfile/grpc_python/Dockerfile index aa29685beee..bce35adc8b6 100644 --- a/tools/dockerfile/grpc_python/Dockerfile +++ b/tools/dockerfile/grpc_python/Dockerfile @@ -40,28 +40,12 @@ RUN make install_c -j12 -C /var/local/git/grpc # Build Python GRPC RUN cd /var/local/git/grpc \ - && pip install src/python/src \ - && pip install src/python/interop + && pip install src/python/grpcio \ + && pip install src/python/grpcio_test # Run Python GRPC's tests -# TODO(nathaniel): It would be nice for these to be auto-discoverable? RUN cd /var/local/git/grpc \ - && python2.7 -B -m grpc._adapter._blocking_invocation_inline_service_test \ - && python2.7 -B -m grpc._adapter._c_test \ - && python2.7 -B -m grpc._adapter._event_invocation_synchronous_event_service_test \ - && python2.7 -B -m grpc._adapter._future_invocation_asynchronous_event_service_test \ - && python2.7 -B -m grpc._adapter._links_test \ - && python2.7 -B -m grpc._adapter._lonely_rear_link_test \ - && python2.7 -B -m grpc._adapter._low_test \ - && python2.7 -B -m grpc.early_adopter.implementations_test \ - && python2.7 -B -m grpc.framework.base.implementations_test \ - && python2.7 -B -m grpc.framework.face.blocking_invocation_inline_service_test \ - && python2.7 -B -m grpc.framework.face.event_invocation_synchronous_event_service_test \ - && python2.7 -B -m grpc.framework.face.future_invocation_asynchronous_event_service_test \ - && python2.7 -B -m grpc.framework.foundation._later_test \ - && python2.7 -B -m grpc.framework.foundation._logging_pool_test \ - && python2.7 -B -m interop._insecure_interop_test \ - && python2.7 -B -m interop._secure_interop_test + && python2.7 -B src/python/grpcio_test/setup.py test # Add a cacerts directory containing the Google root pem file, allowing the interop client to access the production test instance ADD cacerts cacerts diff --git a/tools/profile_analyzer/profile_analyzer.py b/tools/profile_analyzer/profile_analyzer.py index a78f84e5e64..e5e9a28a92d 100755 --- a/tools/profile_analyzer/profile_analyzer.py +++ b/tools/profile_analyzer/profile_analyzer.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/tools/run_tests/antagonist.py b/tools/run_tests/antagonist.py index 111839ccf93..857addfb386 100755 --- a/tools/run_tests/antagonist.py +++ b/tools/run_tests/antagonist.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/tools/run_tests/build_php.sh b/tools/run_tests/build_php.sh index 2fad09e1c4d..1d81779b6ac 100755 --- a/tools/run_tests/build_php.sh +++ b/tools/run_tests/build_php.sh @@ -46,6 +46,3 @@ cd ext/grpc phpize ./configure --enable-grpc=$root make - -# in some jenkins macos machine, somehow the PHP build script can't find libgrpc.dylib -export DYLD_LIBRARY_PATH=$(pwd)/libs/$config diff --git a/tools/run_tests/port_server.py b/tools/run_tests/port_server.py index aab9e4723b2..48b6214b958 100755 --- a/tools/run_tests/port_server.py +++ b/tools/run_tests/port_server.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # diff --git a/tools/run_tests/run_sanity.sh b/tools/run_tests/run_sanity.sh index c18160a891a..4b367dcbc77 100755 --- a/tools/run_tests/run_sanity.sh +++ b/tools/run_tests/run_sanity.sh @@ -44,7 +44,7 @@ cat << EOF | awk '{ print $1 }' | sort > $want_submodules 05b155ff59114735ec8cd089f669c4c3d8f59029 third_party/gflags (v2.1.0-45-g05b155f) c99458533a9b4c743ed51537e25989ea55944908 third_party/googletest (release-1.7.0) 33dd08320648ac71d7d9d732be774ed3818dccc5 third_party/openssl (OpenSSL_1_0_2d) - 23408684b4d2bf1b25e14314413a14d542c18bc4 third_party/protobuf (v3.0.0-alpha-1-1592-g2340868) + 8fce8933649ce09c1661ff2b5b7f6eb79badd251 third_party/protobuf (v3.0.0-alpha-4-1-g8fce893) 50893291621658f355bc5b4d450a8d06a563053d third_party/zlib (v1.2.8) EOF diff --git a/tools/run_tests/run_tests.py b/tools/run_tests/run_tests.py index 13d60e6f7b4..d271137ca12 100755 --- a/tools/run_tests/run_tests.py +++ b/tools/run_tests/run_tests.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # @@ -199,7 +199,9 @@ class GYPCLanguage(object): return [['gyp', '--depth=.', '--suffix=-gyp', 'grpc.gyp']] def make_targets(self): - return gyp_test_paths(False) + # HACK(ctiller): force fling_client and fling_server to be built, as fling_test + # needs these + return gyp_test_paths(False) + ['fling_client', 'fling_server'] def build_steps(self): return [] @@ -725,7 +727,10 @@ def _start_port_server(port_server_port): while True: if waits > 10: port_server.kill() + if port_server.poll() is not None: print "port_server failed to start" + port_log = open('portlog.txt', 'r').read() + print port_log sys.exit(1) try: urllib2.urlopen('http://localhost:%d/get' % port_server_port, diff --git a/tools/run_tests/tests.json b/tools/run_tests/tests.json index 5f4d4d4ebd0..7989f5c100f 100644 --- a/tools/run_tests/tests.json +++ b/tools/run_tests/tests.json @@ -1649,18 +1649,6 @@ "windows" ] }, - { - "ci_platforms": [ - "linux" - ], - "exclude_configs": [], - "flaky": false, - "language": "c++", - "name": "zookeeper_test", - "platforms": [ - "linux" - ] - }, { "ci_platforms": [ "linux",