Merge remote-tracking branch 'upstream/master' into spiffe1

pull/19778/head
Matthew Stevenson 6 years ago
commit 4b7eb25607
  1. 1
      .gitignore
  2. 2
      CMakeLists.txt
  3. 4
      Makefile
  4. 11
      bazel/grpc_build_system.bzl
  5. 16
      bazel/grpc_deps.bzl
  6. 3
      build.yaml
  7. 4
      config.m4
  8. 1
      config.w32
  9. 2
      gRPC-C++.podspec
  10. 4
      gRPC-Core.podspec
  11. 30
      gRPC-ProtoRPC.podspec
  12. 17
      gRPC-RxLibrary.podspec
  13. 116
      gRPC.podspec
  14. 3
      grpc.gyp
  15. 1
      setup.py
  16. 97
      src/compiler/objective_c_generator.cc
  17. 14
      src/compiler/objective_c_generator.h
  18. 60
      src/compiler/objective_c_plugin.cc
  19. 3
      src/core/ext/filters/client_channel/lb_policy/xds/xds_load_balancer_api.h
  20. 2
      src/core/ext/filters/client_channel/resolving_lb_policy.cc
  21. 3
      src/core/lib/channel/channelz.h
  22. 6
      src/core/lib/gpr/log_linux.cc
  23. 71
      src/core/lib/gprpp/map.h
  24. 243
      src/objective-c/BUILD
  25. 2
      src/objective-c/GRPCClient/GRPCCall+ChannelArg.h
  26. 4
      src/objective-c/GRPCClient/GRPCCall+ChannelArg.m
  27. 2
      src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.h
  28. 2
      src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.m
  29. 13
      src/objective-c/GRPCClient/GRPCCall+Cronet.h
  30. 4
      src/objective-c/GRPCClient/GRPCCall+Cronet.m
  31. 2
      src/objective-c/GRPCClient/GRPCCall+GID.h
  32. 4
      src/objective-c/GRPCClient/GRPCCall+OAuth2.h
  33. 2
      src/objective-c/GRPCClient/GRPCCall+Tests.h
  34. 2
      src/objective-c/GRPCClient/GRPCCall+Tests.m
  35. 240
      src/objective-c/GRPCClient/GRPCCall.h
  36. 867
      src/objective-c/GRPCClient/GRPCCall.m
  37. 136
      src/objective-c/GRPCClient/GRPCCallLegacy.h
  38. 677
      src/objective-c/GRPCClient/GRPCCallLegacy.m
  39. 82
      src/objective-c/GRPCClient/GRPCCallOptions.h
  40. 27
      src/objective-c/GRPCClient/GRPCCallOptions.m
  41. 30
      src/objective-c/GRPCClient/GRPCDispatchable.h
  42. 32
      src/objective-c/GRPCClient/GRPCInterceptor.h
  43. 265
      src/objective-c/GRPCClient/GRPCInterceptor.m
  44. 82
      src/objective-c/GRPCClient/GRPCTransport.h
  45. 142
      src/objective-c/GRPCClient/GRPCTransport.m
  46. 187
      src/objective-c/GRPCClient/GRPCTypes.h
  47. 2
      src/objective-c/GRPCClient/internal_testing/GRPCCall+InternalTests.m
  48. 0
      src/objective-c/GRPCClient/private/GRPCCore/ChannelArgsUtil.h
  49. 0
      src/objective-c/GRPCClient/private/GRPCCore/ChannelArgsUtil.m
  50. 6
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCall+V2API.h
  51. 14
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCallInternal.h
  52. 140
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCallInternal.m
  53. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCChannel.h
  54. 72
      src/objective-c/GRPCClient/private/GRPCCore/GRPCChannel.m
  55. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCChannelFactory.h
  56. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCChannelPool+Test.h
  57. 2
      src/objective-c/GRPCClient/private/GRPCCore/GRPCChannelPool.h
  58. 5
      src/objective-c/GRPCClient/private/GRPCCore/GRPCChannelPool.m
  59. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCompletionQueue.h
  60. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCompletionQueue.m
  61. 32
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCoreCronet/GRPCCoreCronetFactory.h
  62. 54
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCoreCronet/GRPCCoreCronetFactory.m
  63. 2
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCoreCronet/GRPCCronetChannelFactory.h
  64. 24
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCoreCronet/GRPCCronetChannelFactory.m
  65. 45
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCoreFactory.h
  66. 90
      src/objective-c/GRPCClient/private/GRPCCore/GRPCCoreFactory.m
  67. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCHost.h
  68. 35
      src/objective-c/GRPCClient/private/GRPCCore/GRPCHost.m
  69. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCInsecureChannelFactory.h
  70. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCInsecureChannelFactory.m
  71. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCOpBatchLog.h
  72. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCOpBatchLog.m
  73. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCReachabilityFlagNames.xmacro.h
  74. 2
      src/objective-c/GRPCClient/private/GRPCCore/GRPCRequestHeaders.h
  75. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCRequestHeaders.m
  76. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCSecureChannelFactory.h
  77. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCSecureChannelFactory.m
  78. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCWrappedCall.h
  79. 0
      src/objective-c/GRPCClient/private/GRPCCore/GRPCWrappedCall.m
  80. 0
      src/objective-c/GRPCClient/private/GRPCCore/NSData+GRPC.h
  81. 0
      src/objective-c/GRPCClient/private/GRPCCore/NSData+GRPC.m
  82. 0
      src/objective-c/GRPCClient/private/GRPCCore/NSDictionary+GRPC.h
  83. 0
      src/objective-c/GRPCClient/private/GRPCCore/NSDictionary+GRPC.m
  84. 0
      src/objective-c/GRPCClient/private/GRPCCore/NSError+GRPC.h
  85. 3
      src/objective-c/GRPCClient/private/GRPCCore/NSError+GRPC.m
  86. 65
      src/objective-c/GRPCClient/private/GRPCTransport+Private.h
  87. 131
      src/objective-c/GRPCClient/private/GRPCTransport+Private.m
  88. 0
      src/objective-c/GRPCClient/version.h
  89. 38
      src/objective-c/ProtoRPC/ProtoRPC.h
  90. 91
      src/objective-c/ProtoRPC/ProtoRPC.m
  91. 67
      src/objective-c/ProtoRPC/ProtoRPCLegacy.h
  92. 121
      src/objective-c/ProtoRPC/ProtoRPCLegacy.m
  93. 22
      src/objective-c/ProtoRPC/ProtoService.h
  94. 42
      src/objective-c/ProtoRPC/ProtoService.m
  95. 23
      src/objective-c/ProtoRPC/ProtoServiceLegacy.h
  96. 71
      src/objective-c/ProtoRPC/ProtoServiceLegacy.m
  97. 2
      src/objective-c/examples/tvOS-sample/tvOS-sample/ViewController.m
  98. 2
      src/objective-c/examples/watchOS-sample/WatchKit-Extension/InterfaceController.m
  99. 11
      src/objective-c/tests/BUILD
  100. 4
      src/objective-c/tests/ConfigureCronet.h
  101. Some files were not shown because too many files have changed in this diff Show More

1
.gitignore vendored

@ -140,6 +140,7 @@ bm_*.json
# Visual Studio Code artifacts
.vscode/*
.history/
# Clion artifacts
cmake-build-debug/

@ -96,8 +96,6 @@ endif()
set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)
add_definitions(-DPB_FIELD_32BIT)
if (MSVC)
include(cmake/msvc_static_runtime.cmake)
add_definitions(-D_WIN32_WINNT=0x600 -D_SCL_SECURE_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS -D_WINSOCK_DEPRECATED_NO_WARNINGS)

@ -354,7 +354,7 @@ CXXFLAGS += -stdlib=libc++
LDFLAGS += -framework CoreFoundation
endif
CXXFLAGS += -Wnon-virtual-dtor
CPPFLAGS += -g -Wall -Wextra -Werror $(W_NO_UNKNOWN_WARNING_OPTION) -Wno-long-long -Wno-unused-parameter -Wno-deprecated-declarations -Wno-sign-conversion -Wno-shadow -Wno-conversion -Wno-implicit-fallthrough -Wno-sign-compare -Wno-missing-field-initializers -Wno-maybe-uninitialized -DPB_FIELD_32BIT -DOSATOMIC_USE_INLINED=1 -Ithird_party/upb -Isrc/core/ext/upb-generated
CPPFLAGS += -g -Wall -Wextra -Werror $(W_NO_UNKNOWN_WARNING_OPTION) -Wno-long-long -Wno-unused-parameter -Wno-deprecated-declarations -Wno-sign-conversion -Wno-shadow -Wno-conversion -Wno-implicit-fallthrough -Wno-sign-compare -Wno-missing-field-initializers -Wno-maybe-uninitialized -DOSATOMIC_USE_INLINED=1 -Ithird_party/upb -Isrc/core/ext/upb-generated
COREFLAGS += -fno-rtti -fno-exceptions
LDFLAGS += -g
@ -451,7 +451,7 @@ USE_BUILT_PROTOC = false
endif
GTEST_LIB = -Ithird_party/googletest/googletest/include -Ithird_party/googletest/googletest third_party/googletest/googletest/src/gtest-all.cc -Ithird_party/googletest/googlemock/include -Ithird_party/googletest/googlemock third_party/googletest/googlemock/src/gmock-all.cc
GTEST_LIB += -lgflags
GTEST_LIB += -lgflags -std=c++11
ifeq ($(V),1)
E = @:
Q =

@ -24,7 +24,6 @@
#
load("//bazel:cc_grpc_library.bzl", "cc_grpc_library")
load("@build_bazel_rules_apple//apple:resources.bzl", "apple_resource_bundle")
load("@upb//bazel:upb_proto_library.bzl", "upb_proto_library")
load("@build_bazel_rules_apple//apple:ios.bzl", "ios_unit_test")
@ -236,19 +235,13 @@ def grpc_cc_binary(name, srcs = [], deps = [], external_deps = [], args = [], da
)
def grpc_generate_one_off_targets():
apple_resource_bundle(
# The choice of name is signicant here, since it determines the bundle name.
name = "gRPCCertificates",
resources = ["etc/roots.pem"],
)
# In open-source, grpc_objc* libraries depend directly on //:grpc
native.alias(
name = "grpc_objc",
actual = "//:grpc",
)
def grpc_objc_use_cronet_config():
def grpc_generate_objc_one_off_targets():
pass
def grpc_sh_test(name, srcs, args = [], data = []):
@ -293,7 +286,7 @@ def grpc_package(name, visibility = "private", features = []):
def grpc_objc_library(
name,
srcs,
srcs = [],
hdrs = [],
textual_hdrs = [],
data = [],

@ -62,7 +62,7 @@ def grpc_deps():
name = "gtest",
actual = "@com_github_google_googletest//:gtest",
)
native.bind(
name = "benchmark",
actual = "@com_github_google_benchmark//:benchmark",
@ -127,9 +127,17 @@ def grpc_deps():
if "com_github_google_googletest" not in native.existing_rules():
http_archive(
name = "com_github_google_googletest",
sha256 = "d0d447b4feeedca837a0d46a289d4223089b32ac2f84545fa4982755cc8919be",
strip_prefix = "googletest-2fe3bd994b3189899d93f1d5a881e725e046fdc2",
url = "https://github.com/google/googletest/archive/2fe3bd994b3189899d93f1d5a881e725e046fdc2.tar.gz",
sha256 = "443d383db648ebb8e391382c0ab63263b7091d03197f304390baac10f178a468",
strip_prefix = "googletest-c9ccac7cb7345901884aabf5d1a786cfa6e2f397",
url = "https://github.com/google/googletest/archive/c9ccac7cb7345901884aabf5d1a786cfa6e2f397.tar.gz", # 2019-08-19
)
if "rules_cc" not in native.existing_rules():
http_archive(
name = "rules_cc",
sha256 = "35f2fb4ea0b3e61ad64a369de284e4fbbdcdba71836a5555abb5e194cf119509",
strip_prefix = "rules_cc-624b5d59dfb45672d4239422fa1e3de1822ee110",
url = "https://github.com/bazelbuild/rules_cc/archive/624b5d59dfb45672d4239422fa1e3de1822ee110.tar.gz", #2019-08-15
)
if "com_github_gflags_gflags" not in native.existing_rules():

@ -6206,8 +6206,7 @@ defaults:
CPPFLAGS: -g -Wall -Wextra -Werror $(W_NO_UNKNOWN_WARNING_OPTION) -Wno-long-long
-Wno-unused-parameter -Wno-deprecated-declarations -Wno-sign-conversion -Wno-shadow
-Wno-conversion -Wno-implicit-fallthrough -Wno-sign-compare -Wno-missing-field-initializers
-Wno-maybe-uninitialized -DPB_FIELD_32BIT -DOSATOMIC_USE_INLINED=1 -Ithird_party/upb
-Isrc/core/ext/upb-generated
-Wno-maybe-uninitialized -DOSATOMIC_USE_INLINED=1 -Ithird_party/upb -Isrc/core/ext/upb-generated
CXXFLAGS: -Wnon-virtual-dtor
LDFLAGS: -g
zlib:

@ -14,8 +14,8 @@ if test "$PHP_GRPC" != "no"; then
LIBS="-lpthread $LIBS"
CFLAGS="-Wall -Werror -Wno-parentheses-equality -Wno-unused-value -std=c11 -g -O2 -D PB_FIELD_32BIT=1"
CXXFLAGS="-std=c++11 -fno-exceptions -fno-rtti -g -O2 -D PB_FIELD_32BIT=1"
CFLAGS="-Wall -Werror -Wno-parentheses-equality -Wno-unused-value -std=c11 -g -O2"
CXXFLAGS="-std=c++11 -fno-exceptions -fno-rtti -g -O2"
GRPC_SHARED_LIBADD="-lpthread $GRPC_SHARED_LIBADD"
PHP_REQUIRE_CXX()
PHP_ADD_LIBRARY(pthread)

@ -706,7 +706,6 @@ if (PHP_GRPC != "no") {
EXTENSION("grpc", grpc_source, null,
"/DOPENSSL_NO_ASM /D_GNU_SOURCE /DWIN32_LEAN_AND_MEAN "+
"/D_HAS_EXCEPTIONS=0 /DNOMINMAX /DGRPC_ARES=0 /D_WIN32_WINNT=0x600 "+
"/DPB_FIELD_32BIT "+
"/I"+configure_module_dirname+" "+
"/I"+configure_module_dirname+"\\include "+
"/I"+configure_module_dirname+"\\src\\core\\ext\\upb-generated "+

@ -56,7 +56,7 @@ Pod::Spec.new do |s|
s.pod_target_xcconfig = {
'HEADER_SEARCH_PATHS' => '"$(inherited)" "$(PODS_TARGET_SRCROOT)/include"',
'USER_HEADER_SEARCH_PATHS' => '"$(PODS_TARGET_SRCROOT)"',
'GCC_PREPROCESSOR_DEFINITIONS' => '"$(inherited)" "COCOAPODS=1" "PB_NO_PACKED_STRUCTS=1"',
'GCC_PREPROCESSOR_DEFINITIONS' => '"$(inherited)" "COCOAPODS=1"',
'CLANG_WARN_STRICT_PROTOTYPES' => 'NO',
'CLANG_WARN_DOCUMENTATION_COMMENTS' => 'NO',

@ -91,12 +91,12 @@ Pod::Spec.new do |s|
# build.
'USE_HEADERMAP' => 'NO',
'ALWAYS_SEARCH_USER_PATHS' => 'NO',
'GCC_PREPROCESSOR_DEFINITIONS' => '"$(inherited)" "COCOAPODS=1" "PB_NO_PACKED_STRUCTS=1"',
'GCC_PREPROCESSOR_DEFINITIONS' => '"$(inherited)" "COCOAPODS=1"',
'CLANG_WARN_STRICT_PROTOTYPES' => 'NO',
}
s.default_subspecs = 'Interface', 'Implementation'
s.compiler_flags = '-DGRPC_ARES=0', '-DPB_FIELD_32BIT'
s.compiler_flags = '-DGRPC_ARES=0'
s.libraries = 'c++'
# Like many other C libraries, gRPC-Core has its public headers under `include/<libname>/` and its

@ -42,22 +42,40 @@ Pod::Spec.new do |s|
s.module_name = name
s.header_dir = name
src_dir = 'src/objective-c/ProtoRPC'
s.default_subspec = 'Main', 'Legacy', 'Legacy-Header'
s.default_subspec = 'Main'
s.subspec 'Legacy-Header' do |ss|
ss.header_mappings_dir = "src/objective-c/ProtoRPC"
ss.public_header_files = "src/objective-c/ProtoRPC/ProtoRPCLegacy.h"
ss.source_files = "src/objective-c/ProtoRPC/ProtoRPCLegacy.h"
end
s.subspec 'Main' do |ss|
ss.header_mappings_dir = "#{src_dir}"
ss.dependency 'gRPC', version
ss.header_mappings_dir = "src/objective-c/ProtoRPC"
ss.dependency "#{s.name}/Legacy-Header", version
ss.dependency 'gRPC/Interface', version
ss.dependency 'Protobuf', '~> 3.0'
ss.source_files = "src/objective-c/ProtoRPC/ProtoMethod.{h,m}",
"src/objective-c/ProtoRPC/ProtoRPC.{h,m}",
"src/objective-c/ProtoRPC/ProtoService.{h,m}"
end
s.subspec 'Legacy' do |ss|
ss.header_mappings_dir = "src/objective-c/ProtoRPC"
ss.dependency "#{s.name}/Main", version
ss.dependency "#{s.name}/Legacy-Header", version
ss.dependency 'gRPC/GRPCCore', version
ss.dependency 'gRPC-RxLibrary', version
ss.dependency 'Protobuf', '~> 3.0'
ss.source_files = "#{src_dir}/*.{h,m}"
ss.source_files = "src/objective-c/ProtoRPC/ProtoRPCLegacy.m",
"src/objective-c/ProtoRPC/ProtoServiceLegacy.m"
end
# CFStream is now default. Leaving this subspec only for compatibility purpose.
s.subspec 'CFStream' do |ss|
ss.dependency "#{s.name}/Main", version
ss.dependency "#{s.name}/Legacy", version
end
s.pod_target_xcconfig = {

@ -42,6 +42,23 @@ Pod::Spec.new do |s|
s.module_name = name
s.header_dir = name
s.default_subspec = 'Interface', 'Implementation'
src_dir = 'src/objective-c/RxLibrary'
s.subspec 'Interface' do |ss|
ss.header_mappings_dir = "#{src_dir}"
ss.source_files = "#{src_dir}/*.h"
ss.public_header_files = "#{src_dir}/*.h"
end
s.subspec 'Implementation' do |ss|
ss.header_mappings_dir = "#{src_dir}"
ss.source_files = "#{src_dir}/*.m", "#{src_dir}/**/*.{h,m}"
ss.private_header_files = "#{src_dir}/**/*.h"
ss.dependency "#{s.name}/Interface"
end
src_dir = 'src/objective-c/RxLibrary'
s.source_files = "#{src_dir}/*.{h,m}", "#{src_dir}/**/*.{h,m}"
s.private_header_files = "#{src_dir}/private/*.h"

@ -41,13 +41,7 @@ Pod::Spec.new do |s|
s.module_name = name
s.header_dir = name
src_dir = 'src/objective-c/GRPCClient'
s.dependency 'gRPC-RxLibrary', version
s.default_subspec = 'Main'
# Certificates, to be able to establish TLS connections:
s.resource_bundles = { 'gRPCCertificates' => ['etc/roots.pem'] }
s.default_subspec = 'Interface', 'GRPCCore', 'Interface-Legacy'
s.pod_target_xcconfig = {
# This is needed by all pods that depend on gRPC-RxLibrary:
@ -55,29 +49,103 @@ Pod::Spec.new do |s|
'CLANG_WARN_STRICT_PROTOTYPES' => 'NO',
}
s.subspec 'Main' do |ss|
ss.header_mappings_dir = "#{src_dir}"
ss.source_files = "#{src_dir}/*.{h,m}", "#{src_dir}/**/*.{h,m}"
ss.exclude_files = "#{src_dir}/GRPCCall+GID.{h,m}"
ss.private_header_files = "#{src_dir}/private/*.h", "#{src_dir}/internal/*.h"
ss.dependency 'gRPC-Core', version
s.subspec 'Interface-Legacy' do |ss|
ss.header_mappings_dir = 'src/objective-c/GRPCClient'
ss.public_header_files = "GRPCClient/GRPCCall+ChannelArg.h",
"GRPCClient/GRPCCall+ChannelCredentials.h",
"GRPCClient/GRPCCall+Cronet.h",
"GRPCClient/GRPCCall+OAuth2.h",
"GRPCClient/GRPCCall+Tests.h",
"src/objective-c/GRPCClient/GRPCCallLegacy.h",
"src/objective-c/GRPCClient/GRPCTypes.h"
ss.source_files = "GRPCClient/GRPCCall+ChannelArg.h",
"GRPCClient/GRPCCall+ChannelCredentials.h",
"GRPCClient/GRPCCall+Cronet.h",
"GRPCClient/GRPCCall+OAuth2.h",
"GRPCClient/GRPCCall+Tests.h",
"src/objective-c/GRPCClient/GRPCCallLegacy.h",
"src/objective-c/GRPCClient/GRPCTypes.h"
ss.dependency "gRPC-RxLibrary/Interface", version
end
# CFStream is now default. Leaving this subspec only for compatibility purpose.
s.subspec 'CFStream' do |ss|
ss.dependency "#{s.name}/Main", version
s.subspec 'Interface' do |ss|
ss.header_mappings_dir = 'src/objective-c/GRPCClient'
ss.public_header_files = 'src/objective-c/GRPCClient/GRPCCall.h',
'src/objective-c/GRPCClient/GRPCCall+Interceptor.h',
'src/objective-c/GRPCClient/GRPCCallOptions.h',
'src/objective-c/GRPCClient/GRPCInterceptor.h',
'src/objective-c/GRPCClient/GRPCTransport.h',
'src/objective-c/GRPCClient/GRPCDispatchable.h',
'src/objective-c/GRPCClient/version.h'
ss.source_files = 'src/objective-c/GRPCClient/GRPCCall.h',
'src/objective-c/GRPCClient/GRPCCall.m',
'src/objective-c/GRPCClient/GRPCCall+Interceptor.h',
'src/objective-c/GRPCClient/GRPCCall+Interceptor.m',
'src/objective-c/GRPCClient/GRPCCallOptions.h',
'src/objective-c/GRPCClient/GRPCCallOptions.m',
'src/objective-c/GRPCClient/GRPCDispatchable.h',
'src/objective-c/GRPCClient/GRPCInterceptor.h',
'src/objective-c/GRPCClient/GRPCInterceptor.m',
'src/objective-c/GRPCClient/GRPCTransport.h',
'src/objective-c/GRPCClient/GRPCTransport.m',
'src/objective-c/GRPCClient/internal/*.h',
'src/objective-c/GRPCClient/private/GRPCTransport+Private.h',
'src/objective-c/GRPCClient/private/GRPCTransport+Private.m',
'src/objective-c/GRPCClient/version.h'
ss.dependency "#{s.name}/Interface-Legacy", version
end
s.subspec 'GID' do |ss|
ss.ios.deployment_target = '7.0'
s.subspec 'GRPCCore' do |ss|
ss.header_mappings_dir = 'src/objective-c/GRPCClient'
ss.public_header_files = 'src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.h',
'src/objective-c/GRPCClient/GRPCCall+Cronet.h',
'src/objective-c/GRPCClient/GRPCCall+OAuth2.h',
'src/objective-c/GRPCClient/GRPCCall+Tests.h',
'src/objective-c/GRPCClient/GRPCCall+ChannelArg.h',
'src/objective-c/GRPCClient/internal_testing/*.h'
ss.private_header_files = 'src/objective-c/GRPCClient/private/GRPCCore/*.h'
ss.source_files = 'src/objective-c/GRPCClient/internal_testing/*.{h,m}',
'src/objective-c/GRPCClient/private/GRPCCore/*.{h,m}',
'src/objective-c/GRPCClient/GRPCCall+ChannelArg.h',
'src/objective-c/GRPCClient/GRPCCall+ChannelArg.m',
'src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.h',
'src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.m',
'src/objective-c/GRPCClient/GRPCCall+Cronet.h',
'src/objective-c/GRPCClient/GRPCCall+Cronet.m',
'src/objective-c/GRPCClient/GRPCCall+OAuth2.h',
'src/objective-c/GRPCClient/GRPCCall+OAuth2.m',
'src/objective-c/GRPCClient/GRPCCall+Tests.h',
'src/objective-c/GRPCClient/GRPCCall+Tests.m',
'src/objective-c/GRPCClient/GRPCCallLegacy.m'
# Certificates, to be able to establish TLS connections:
ss.resource_bundles = { 'gRPCCertificates' => ['etc/roots.pem'] }
ss.dependency "#{s.name}/Interface-Legacy", version
ss.dependency "#{s.name}/Interface", version
ss.dependency 'gRPC-Core', version
ss.dependency 'gRPC-RxLibrary', version
end
ss.header_mappings_dir = "#{src_dir}"
s.subspec 'GRPCCoreCronet' do |ss|
ss.header_mappings_dir = 'src/objective-c/GRPCClient'
ss.source_files = "#{src_dir}/GRPCCall+GID.{h,m}"
ss.source_files = 'src/objective-c/GRPCClient/GRPCCall+Cronet.h',
'src/objective-c/GRPCClient/GRPCCall+Cronet.m',
'src/objective-c/GRPCClient/private/GRPCCore/GRPCCoreCronet/*.{h,m}'
ss.dependency "#{s.name}/GRPCCore", version
ss.dependency 'gRPC-Core/Cronet-Implementation', version
ss.dependency 'CronetFramework'
end
ss.dependency "#{s.name}/Main", version
ss.dependency 'Google/SignIn'
# CFStream is now default. Leaving this subspec only for compatibility purpose.
s.subspec 'CFStream' do |ss|
ss.dependency "#{s.name}/GRPCCore", version
end
end

@ -66,7 +66,6 @@
'-Wno-sign-compare',
'-Wno-missing-field-initializers',
'-Wno-maybe-uninitialized',
'-DPB_FIELD_32BIT',
'-DOSATOMIC_USE_INLINED=1',
'-Ithird_party/upb',
'-Isrc/core/ext/upb-generated',
@ -155,7 +154,6 @@
'-Wno-sign-compare',
'-Wno-missing-field-initializers',
'-Wno-maybe-uninitialized',
'-DPB_FIELD_32BIT',
'-DOSATOMIC_USE_INLINED=1',
'-Ithird_party/upb',
'-Isrc/core/ext/upb-generated',
@ -176,7 +174,6 @@
'-Wno-sign-compare',
'-Wno-missing-field-initializers',
'-Wno-maybe-uninitialized',
'-DPB_FIELD_32BIT',
'-DOSATOMIC_USE_INLINED=1',
'-Ithird_party/upb',
'-Isrc/core/ext/upb-generated',

@ -161,7 +161,6 @@ if EXTRA_ENV_COMPILE_ARGS is None:
EXTRA_ENV_COMPILE_ARGS += ' -std=gnu99 -fvisibility=hidden -fno-wrapv -fno-exceptions'
elif "darwin" in sys.platform:
EXTRA_ENV_COMPILE_ARGS += ' -stdlib=libc++ -fvisibility=hidden -fno-wrapv -fno-exceptions'
EXTRA_ENV_COMPILE_ARGS += ' -DPB_FIELD_32BIT'
if EXTRA_ENV_LINK_ARGS is None:
EXTRA_ENV_LINK_ARGS = ''

@ -238,19 +238,21 @@ void PrintV2Implementation(Printer* printer, const MethodDescriptor* method,
}
void PrintMethodImplementations(Printer* printer,
const MethodDescriptor* method) {
const MethodDescriptor* method,
const Parameters& generator_params) {
map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
// TODO(jcanizales): Print documentation from the method.
printer->Print("// Deprecated methods.\n");
PrintSimpleSignature(printer, method, vars);
PrintSimpleImplementation(printer, method, vars);
if (!generator_params.no_v1_compatibility) {
// TODO(jcanizales): Print documentation from the method.
PrintSimpleSignature(printer, method, vars);
PrintSimpleImplementation(printer, method, vars);
printer->Print("// Returns a not-yet-started RPC object.\n");
PrintAdvancedSignature(printer, method, vars);
PrintAdvancedImplementation(printer, method, vars);
printer->Print("// Returns a not-yet-started RPC object.\n");
PrintAdvancedSignature(printer, method, vars);
PrintAdvancedImplementation(printer, method, vars);
}
PrintV2Signature(printer, method, vars);
PrintV2Implementation(printer, method, vars);
@ -276,9 +278,12 @@ void PrintMethodImplementations(Printer* printer,
return output;
}
::grpc::string GetProtocol(const ServiceDescriptor* service) {
::grpc::string GetProtocol(const ServiceDescriptor* service,
const Parameters& generator_params) {
::grpc::string output;
if (generator_params.no_v1_compatibility) return output;
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
@ -321,7 +326,8 @@ void PrintMethodImplementations(Printer* printer,
return output;
}
::grpc::string GetInterface(const ServiceDescriptor* service) {
::grpc::string GetInterface(const ServiceDescriptor* service,
const Parameters& generator_params) {
::grpc::string output;
// Scope the output stream so it closes and finalizes output to the string.
@ -338,7 +344,11 @@ void PrintMethodImplementations(Printer* printer,
" */\n");
printer.Print(vars,
"@interface $service_class$ :"
" GRPCProtoService<$service_class$, $service_class$2>\n");
" GRPCProtoService<$service_class$2");
if (!generator_params.no_v1_compatibility) {
printer.Print(vars, ", $service_class$");
}
printer.Print(">\n");
printer.Print(
"- (instancetype)initWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions "
@ -347,17 +357,20 @@ void PrintMethodImplementations(Printer* printer,
printer.Print(
"+ (instancetype)serviceWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions *_Nullable)callOptions;\n");
printer.Print(
"// The following methods belong to a set of old APIs that have been "
"deprecated.\n");
printer.Print("- (instancetype)initWithHost:(NSString *)host;\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
if (!generator_params.no_v1_compatibility) {
printer.Print(
"// The following methods belong to a set of old APIs that have been "
"deprecated.\n");
printer.Print("- (instancetype)initWithHost:(NSString *)host;\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
}
printer.Print("@end\n");
return output;
}
::grpc::string GetSource(const ServiceDescriptor* service) {
::grpc::string GetSource(const ServiceDescriptor* service,
const Parameters& generator_params) {
::grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@ -381,22 +394,28 @@ void PrintMethodImplementations(Printer* printer,
" packageName:@\"$package$\"\n"
" serviceName:@\"$service_name$\"\n"
" callOptions:callOptions];\n"
"}\n\n"
"- (instancetype)initWithHost:(NSString *)host {\n"
" return [super initWithHost:host\n"
" packageName:@\"$package$\"\n"
" serviceName:@\"$service_name$\"];\n"
"}\n\n"
"#pragma clang diagnostic pop\n\n");
"}\n\n");
if (!generator_params.no_v1_compatibility) {
printer.Print(vars,
"- (instancetype)initWithHost:(NSString *)host {\n"
" return [super initWithHost:host\n"
" packageName:@\"$package$\"\n"
" serviceName:@\"$service_name$\"];\n"
"}\n\n");
}
printer.Print("#pragma clang diagnostic pop\n\n");
if (!generator_params.no_v1_compatibility) {
printer.Print(
"// Override superclass initializer to disallow different"
" package and service names.\n"
"- (instancetype)initWithHost:(NSString *)host\n"
" packageName:(NSString *)packageName\n"
" serviceName:(NSString *)serviceName {\n"
" return [self initWithHost:host];\n"
"}\n\n");
}
printer.Print(
"// Override superclass initializer to disallow different"
" package and service names.\n"
"- (instancetype)initWithHost:(NSString *)host\n"
" packageName:(NSString *)packageName\n"
" serviceName:(NSString *)serviceName {\n"
" return [self initWithHost:host];\n"
"}\n\n"
"- (instancetype)initWithHost:(NSString *)host\n"
" packageName:(NSString *)packageName\n"
" serviceName:(NSString *)serviceName\n"
@ -404,11 +423,14 @@ void PrintMethodImplementations(Printer* printer,
" return [self initWithHost:host callOptions:callOptions];\n"
"}\n\n");
printer.Print("#pragma mark - Class Methods\n\n");
if (!generator_params.no_v1_compatibility) {
printer.Print(
"+ (instancetype)serviceWithHost:(NSString *)host {\n"
" return [[self alloc] initWithHost:host];\n"
"}\n\n");
}
printer.Print(
"#pragma mark - Class Methods\n\n"
"+ (instancetype)serviceWithHost:(NSString *)host {\n"
" return [[self alloc] initWithHost:host];\n"
"}\n\n"
"+ (instancetype)serviceWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions *_Nullable)callOptions {\n"
" return [[self alloc] initWithHost:host callOptions:callOptions];\n"
@ -417,7 +439,8 @@ void PrintMethodImplementations(Printer* printer,
printer.Print("#pragma mark - Method Implementations\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodImplementations(&printer, service->method(i));
PrintMethodImplementations(&printer, service->method(i),
generator_params);
}
printer.Print("@end\n");

@ -23,6 +23,11 @@
namespace grpc_objective_c_generator {
struct Parameters {
// Do not generate V1 interface and implementation
bool no_v1_compatibility;
};
using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
@ -34,7 +39,8 @@ string GetAllMessageClasses(const FileDescriptor* file);
// Returns the content to be included defining the @protocol segment at the
// insertion point of the generated implementation file. This interface is
// legacy and for backwards compatibility.
string GetProtocol(const ServiceDescriptor* service);
string GetProtocol(const ServiceDescriptor* service,
const Parameters& generator_params);
// Returns the content to be included defining the @protocol segment at the
// insertion point of the generated implementation file.
@ -42,11 +48,13 @@ string GetV2Protocol(const ServiceDescriptor* service);
// Returns the content to be included defining the @interface segment at the
// insertion point of the generated implementation file.
string GetInterface(const ServiceDescriptor* service);
string GetInterface(const ServiceDescriptor* service,
const Parameters& generator_params);
// Returns the content to be included in the "global_scope" insertion point of
// the generated implementation file.
string GetSource(const ServiceDescriptor* service);
string GetSource(const ServiceDescriptor* service,
const Parameters& generator_params);
} // namespace grpc_objective_c_generator

@ -111,6 +111,22 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
::grpc::string file_name =
google::protobuf::compiler::objectivec::FilePath(file);
grpc_objective_c_generator::Parameters generator_params;
generator_params.no_v1_compatibility = false;
if (!parameter.empty()) {
std::vector<grpc::string> parameters_list =
grpc_generator::tokenize(parameter, ",");
for (auto parameter_string = parameters_list.begin();
parameter_string != parameters_list.end(); parameter_string++) {
std::vector<grpc::string> param =
grpc_generator::tokenize(*parameter_string, "=");
if (param[0] == "no_v1_compatibility") {
generator_params.no_v1_compatibility = true;
}
}
}
{
// Generate .pbrpc.h
@ -121,18 +137,25 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
imports = FrameworkImport(file_name + ".pbobjc.h", framework);
}
::grpc::string system_imports = SystemImport("ProtoRPC/ProtoService.h") +
SystemImport("ProtoRPC/ProtoRPC.h") +
SystemImport("RxLibrary/GRXWriteable.h") +
SystemImport("RxLibrary/GRXWriter.h");
::grpc::string system_imports =
SystemImport("ProtoRPC/ProtoService.h") +
(generator_params.no_v1_compatibility
? SystemImport("ProtoRPC/ProtoRPC.h")
: SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
if (!generator_params.no_v1_compatibility) {
system_imports += SystemImport("RxLibrary/GRXWriteable.h") +
SystemImport("RxLibrary/GRXWriter.h");
}
::grpc::string forward_declarations =
"@class GRPCProtoCall;\n"
"@class GRPCUnaryProtoCall;\n"
"@class GRPCStreamingProtoCall;\n"
"@class GRPCCallOptions;\n"
"@protocol GRPCProtoResponseHandler;\n"
"\n";
"@protocol GRPCProtoResponseHandler;\n";
if (!generator_params.no_v1_compatibility) {
forward_declarations += "@class GRPCProtoCall;\n";
}
forward_declarations += "\n";
::grpc::string class_declarations =
grpc_objective_c_generator::GetAllMessageClasses(file);
@ -152,13 +175,15 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
::grpc::string protocols;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
protocols += grpc_objective_c_generator::GetProtocol(service);
protocols +=
grpc_objective_c_generator::GetProtocol(service, generator_params);
}
::grpc::string interfaces;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
interfaces += grpc_objective_c_generator::GetInterface(service);
interfaces +=
grpc_objective_c_generator::GetInterface(service, generator_params);
}
Write(context, file_name + ".pbrpc.h",
@ -178,14 +203,16 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
::grpc::string imports;
if (framework.empty()) {
imports = LocalImport(file_name + ".pbrpc.h") +
LocalImport(file_name + ".pbobjc.h") +
SystemImport("ProtoRPC/ProtoRPC.h") +
SystemImport("RxLibrary/GRXWriter+Immediate.h");
LocalImport(file_name + ".pbobjc.h");
} else {
imports = FrameworkImport(file_name + ".pbrpc.h", framework) +
FrameworkImport(file_name + ".pbobjc.h", framework) +
SystemImport("ProtoRPC/ProtoRPC.h") +
SystemImport("RxLibrary/GRXWriter+Immediate.h");
FrameworkImport(file_name + ".pbobjc.h", framework);
}
imports += (generator_params.no_v1_compatibility
? SystemImport("ProtoRPC/ProtoRPC.h")
: SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
if (!generator_params.no_v1_compatibility) {
imports += SystemImport("RxLibrary/GRXWriter+Immediate.h");
}
::grpc::string class_imports;
@ -196,7 +223,8 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
::grpc::string definitions;
for (int i = 0; i < file->service_count(); i++) {
const grpc::protobuf::ServiceDescriptor* service = file->service(i);
definitions += grpc_objective_c_generator::GetSource(service);
definitions +=
grpc_objective_c_generator::GetSource(service, generator_params);
}
Write(context, file_name + ".pbrpc.m",

@ -37,7 +37,8 @@ struct XdsLocalityInfo {
// This comparator only compares the locality names.
struct Less {
bool operator()(const XdsLocalityInfo& lhs, const XdsLocalityInfo& rhs) {
bool operator()(const XdsLocalityInfo& lhs,
const XdsLocalityInfo& rhs) const {
return XdsLocalityName::Less()(lhs.locality_name, rhs.locality_name);
}
};

@ -160,6 +160,8 @@ class ResolvingLoadBalancingPolicy::ResolvingControlHelper
}
}
void AddTraceEvent(TraceSeverity severity, const char* message) override {}
void set_child(LoadBalancingPolicy* child) { child_ = child; }
private:

@ -81,7 +81,10 @@ class BaseNode : public RefCounted<BaseNode> {
kSocket,
};
protected:
BaseNode(EntityType type, UniquePtr<char> name);
public:
virtual ~BaseNode();
// All children must implement this function.

@ -40,7 +40,9 @@
#include <time.h>
#include <unistd.h>
static long gettid(void) { return syscall(__NR_gettid); }
// Not naming it as gettid() to avoid duplicate declarations when complied with
// GCC 9.1.
static long local_gettid(void) { return syscall(__NR_gettid); }
void gpr_log(const char* file, int line, gpr_log_severity severity,
const char* format, ...) {
@ -70,7 +72,7 @@ void gpr_default_log(gpr_log_func_args* args) {
gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
struct tm tm;
static __thread long tid = 0;
if (tid == 0) tid = gettid();
if (tid == 0) tid = local_gettid();
timer = static_cast<time_t>(now.tv_sec);
final_slash = strrchr(args->file, '/');

@ -63,6 +63,7 @@ class Map {
typedef Pair<key_type, mapped_type> value_type;
typedef Compare key_compare;
class iterator;
class const_iterator;
Map() = default;
~Map() { clear(); }
@ -83,6 +84,22 @@ class Map {
return *this;
}
// Copyable.
Map(const Map& other) {
for (const auto& p : other) {
emplace(p);
}
}
Map& operator=(const Map& other) {
if (this != &other) {
clear();
for (const auto& p : other) {
emplace(p);
}
}
return *this;
}
T& operator[](key_type&& key);
T& operator[](const key_type& key);
iterator find(const key_type& k);
@ -117,6 +134,13 @@ class Map {
iterator end() { return iterator(this, nullptr); }
const_iterator begin() const {
Entry* curr = GetMinEntry(root_);
return const_iterator(this, curr);
}
const_iterator end() const { return const_iterator(this, nullptr); }
iterator lower_bound(const Key& k) {
// This is a workaround for "const key_compare compare;"
// because some versions of compilers cannot build this by requiring
@ -209,6 +233,53 @@ class Map<Key, T, Compare>::iterator
GrpcMap* map_;
};
template <class Key, class T, class Compare>
class Map<Key, T, Compare>::const_iterator
: public std::iterator<std::input_iterator_tag, Pair<Key, T>, int32_t,
Pair<Key, T>*, Pair<Key, T>&> {
public:
const_iterator(const const_iterator& iter)
: curr_(iter.curr_), map_(iter.map_) {}
bool operator==(const const_iterator& rhs) const {
return (curr_ == rhs.curr_);
}
bool operator!=(const const_iterator& rhs) const {
return (curr_ != rhs.curr_);
}
const_iterator& operator++() {
curr_ = map_->InOrderSuccessor(curr_);
return *this;
}
const_iterator operator++(int) {
Entry* prev = curr_;
curr_ = map_->InOrderSuccessor(curr_);
return const_iterator(map_, prev);
}
const_iterator& operator=(const const_iterator& other) {
if (this != &other) {
this->curr_ = other.curr_;
this->map_ = other.map_;
}
return *this;
}
// operator*()
const value_type& operator*() const { return curr_->pair; }
// operator->()
const value_type* operator->() const { return &curr_->pair; }
private:
friend class Map<key_type, mapped_type, key_compare>;
using GrpcMap = typename ::grpc_core::Map<Key, T, Compare>;
const_iterator(const GrpcMap* map, Entry* curr) : curr_(curr), map_(map) {}
Entry* curr_;
const GrpcMap* map_;
};
template <class Key, class T, class Compare>
T& Map<Key, T, Compare>::operator[](key_type&& key) {
auto iter = find(key);

@ -18,24 +18,30 @@ licenses(["notice"]) # Apache v2
package(default_visibility = ["//visibility:public"])
load("//bazel:grpc_build_system.bzl", "grpc_objc_library", "grpc_objc_use_cronet_config")
load("//bazel:grpc_build_system.bzl", "grpc_objc_library", "grpc_generate_objc_one_off_targets")
exports_files(["LICENSE"])
grpc_objc_use_cronet_config()
grpc_generate_objc_one_off_targets()
grpc_objc_library(
name = "rx_library_headers",
hdrs = glob([
"RxLibrary/*.h",
]),
includes = ["."],
)
grpc_objc_library(
name = "rx_library",
srcs = glob([
"RxLibrary/*.m",
"RxLibrary/transformations/*.m",
]),
hdrs = glob([
"RxLibrary/*.h",
"RxLibrary/transformations/*.h",
]),
includes = ["."],
deps = [":rx_library_private"],
deps = [
":rx_library_headers",
":rx_library_private",
],
)
grpc_objc_library(
@ -50,84 +56,195 @@ grpc_objc_library(
)
grpc_objc_library(
name = "grpc_objc_client",
srcs = glob(
[
"GRPCClient/*.m",
"GRPCClient/private/*.m",
],
exclude = ["GRPCClient/GRPCCall+GID.m"],
),
hdrs = glob(
[
"GRPCClient/*.h",
"GRPCClient/internal/*.h",
],
exclude = ["GRPCClient/GRPCCall+GID.h"],
),
data = ["//:gRPCCertificates"],
name = "grpc_objc_interface_legacy",
hdrs = [
"GRPCClient/GRPCCall+ChannelArg.h",
"GRPCClient/GRPCCall+ChannelCredentials.h",
"GRPCClient/GRPCCall+Cronet.h",
"GRPCClient/GRPCCall+OAuth2.h",
"GRPCClient/GRPCCall+Tests.h",
"GRPCClient/GRPCCallLegacy.h",
"GRPCClient/GRPCTypes.h",
],
deps = [
"rx_library_headers",
],
)
grpc_objc_library(
name = "grpc_objc_interface",
hdrs = [
"GRPCClient/GRPCCall.h",
"GRPCClient/GRPCCall+Interceptor.h",
"GRPCClient/GRPCCallOptions.h",
"GRPCClient/GRPCInterceptor.h",
"GRPCClient/GRPCTransport.h",
"GRPCClient/GRPCDispatchable.h",
"GRPCClient/internal/GRPCCallOptions+Internal.h",
"GRPCClient/version.h",
],
srcs = [
"GRPCClient/GRPCCall.m",
"GRPCClient/GRPCCall+Interceptor.m",
"GRPCClient/GRPCCallOptions.m",
"GRPCClient/GRPCInterceptor.m",
"GRPCClient/GRPCTransport.m",
"GRPCClient/private/GRPCTransport+Private.m",
],
includes = ["."],
textual_hdrs = glob([
"GRPCClient/private/*.h",
]),
textual_hdrs = [
"GRPCClient/private/GRPCTransport+Private.h",
],
deps = [
":grpc_objc_interface_legacy",
],
)
grpc_objc_library(
name = "grpc_objc_client_core",
hdrs = [
"GRPCClient/GRPCCall+ChannelCredentials.h",
"GRPCClient/GRPCCall+Cronet.h",
"GRPCClient/GRPCCall+OAuth2.h",
"GRPCClient/GRPCCall+Tests.h",
"GRPCClient/GRPCCall+ChannelArg.h",
],
textual_hdrs = glob(["GRPCClient/private/GRPCCore/*.h"]),
srcs = [
"GRPCClient/GRPCCall+ChannelArg.m",
"GRPCClient/GRPCCall+ChannelCredentials.m",
"GRPCClient/GRPCCall+Cronet.m",
"GRPCClient/GRPCCall+OAuth2.m",
"GRPCClient/GRPCCall+Tests.m",
"GRPCClient/GRPCCallLegacy.m",
] + glob(["GRPCClient/private/GRPCCore/*.m"]),
data = [":gRPCCertificates"],
includes = ["."],
deps = [
":grpc_objc_interface",
":grpc_objc_interface_legacy",
":rx_library",
"//:grpc_objc",
],
)
alias(
name = "grpc_objc_client",
actual = "grpc_objc_client_core",
)
grpc_objc_library(
name = "proto_objc_rpc_legacy_header",
hdrs = [
"ProtoRPC/ProtoRPCLegacy.h",
],
includes = ["."],
)
grpc_objc_library(
name = "proto_objc_rpc",
srcs = glob(
["ProtoRPC/*.m"],
),
hdrs = glob(
["ProtoRPC/*.h"],
),
# Different from Cocoapods, do not import as if @com_google_protobuf//:protobuf_objc is a framework,
# use the real paths of @com_google_protobuf//:protobuf_objc instead
name = "proto_objc_rpc_v2",
srcs = [
"ProtoRPC/ProtoMethod.m",
"ProtoRPC/ProtoRPC.m",
"ProtoRPC/ProtoService.m",
],
hdrs = [
"ProtoRPC/ProtoMethod.h",
"ProtoRPC/ProtoRPC.h",
"ProtoRPC/ProtoService.h",
],
includes = ["."],
defines = ["GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=0"],
deps = [
":grpc_objc_client",
":grpc_objc_interface",
":proto_objc_rpc_legacy_header",
"@com_google_protobuf//:protobuf_objc",
],
)
grpc_objc_library(
name = "proto_objc_rpc",
srcs = [
"ProtoRPC/ProtoRPCLegacy.m",
"ProtoRPC/ProtoServiceLegacy.m",
],
hdrs = [
"ProtoRPC/ProtoMethod.h",
"ProtoRPC/ProtoRPCLegacy.h",
"ProtoRPC/ProtoService.h",
],
deps = [
":rx_library",
":proto_objc_rpc_v2",
":proto_objc_rpc_legacy_header",
":grpc_objc_client_core",
"@com_google_protobuf//:protobuf_objc",
],
)
load("@build_bazel_rules_apple//apple:resources.bzl", "apple_resource_bundle")
apple_resource_bundle(
# The choice of name is signicant here, since it determines the bundle name.
name = "gRPCCertificates",
resources = ["//:etc/roots.pem"],
)
# Internal target combining grpc_objc_client_core and proto_objc_rpc for testing
grpc_objc_library(
name = "grpc_objc_client_internal_testing",
srcs = glob(
[
"GRPCClient/*.m",
"GRPCClient/private/*.m",
"GRPCClient/internal_testing/*.m",
"ProtoRPC/*.m",
],
exclude = ["GRPCClient/GRPCCall+GID.m"],
),
hdrs = glob(
[
"GRPCClient/*.h",
"GRPCClient/internal/*.h",
"GRPCClient/internal_testing/*.h",
"ProtoRPC/*.h",
],
exclude = ["GRPCClient/GRPCCall+GID.h"],
),
name = "grpc_objc_client_core_internal_testing",
hdrs = [
"GRPCClient/GRPCCall+ChannelCredentials.h",
"GRPCClient/GRPCCall+Cronet.h",
"GRPCClient/GRPCCall+OAuth2.h",
"GRPCClient/GRPCCall+Tests.h",
"GRPCClient/GRPCCall+ChannelArg.h",
"GRPCClient/internal_testing/GRPCCall+InternalTests.h",
],
textual_hdrs = glob(["GRPCClient/private/GRPCCore/*.h"]),
srcs = [
"GRPCClient/GRPCCall+ChannelArg.m",
"GRPCClient/GRPCCall+ChannelCredentials.m",
"GRPCClient/GRPCCall+Cronet.m",
"GRPCClient/GRPCCall+OAuth2.m",
"GRPCClient/GRPCCall+Tests.m",
"GRPCClient/GRPCCallLegacy.m",
"GRPCClient/internal_testing/GRPCCall+InternalTests.m",
] + glob(["GRPCClient/private/GRPCCore/*.m"]),
data = [":gRPCCertificates"],
includes = ["."],
data = ["//:gRPCCertificates"],
defines = [
"GRPC_TEST_OBJC=1",
"GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=0",
],
textual_hdrs = glob(
[
"GRPCClient/private/*.h",
],
),
deps = [
":grpc_objc_interface",
":grpc_objc_interface_legacy",
":rx_library",
"//:grpc_objc",
],
)
grpc_objc_library(
name = "proto_objc_rpc_internal_testing",
srcs = [
"ProtoRPC/ProtoRPCLegacy.m",
"ProtoRPC/ProtoServiceLegacy.m",
],
hdrs = [
"ProtoRPC/ProtoMethod.h",
"ProtoRPC/ProtoRPCLegacy.h",
"ProtoRPC/ProtoService.h",
],
deps = [
":rx_library",
":proto_objc_rpc_v2",
":proto_objc_rpc_legacy_header",
":grpc_objc_client_core_internal_testing",
"@com_google_protobuf//:protobuf_objc",
],
)
alias(
name = "grpc_objc_client_internal_testing",
actual = "proto_objc_rpc_internal_testing",
)

@ -15,7 +15,7 @@
* limitations under the License.
*
*/
#import "GRPCCall.h"
#import "GRPCCallLegacy.h"
#include <AvailabilityMacros.h>

@ -18,8 +18,8 @@
#import "GRPCCall+ChannelArg.h"
#import "private/GRPCChannelPool.h"
#import "private/GRPCHost.h"
#import "private/GRPCCore/GRPCChannelPool.h"
#import "private/GRPCCore/GRPCHost.h"
#import <grpc/impl/codegen/compression_types.h>

@ -16,7 +16,7 @@
*
*/
#import "GRPCCall.h"
#import "GRPCCallLegacy.h"
// Deprecated interface. Please use GRPCCallOptions instead.
@interface GRPCCall (ChannelCredentials)

@ -18,7 +18,7 @@
#import "GRPCCall+ChannelCredentials.h"
#import "private/GRPCHost.h"
#import "private/GRPCCore/GRPCHost.h"
@implementation GRPCCall (ChannelCredentials)

@ -15,12 +15,16 @@
* limitations under the License.
*
*/
#ifdef GRPC_COMPILE_WITH_CRONET
#import <Cronet/Cronet.h>
#import "GRPCCall.h"
#import "GRPCCallLegacy.h"
#import "GRPCTypes.h"
// Deprecated interface. Please use GRPCCallOptions instead.
typedef struct stream_engine stream_engine;
// Transport id for Cronet transport
extern const GRPCTransportId gGRPCCoreCronetId;
// Deprecated class. Please use the gGRPCCoreCronetId with GRPCCallOptions.transport instead.
@interface GRPCCall (Cronet)
+ (void)useCronetWithEngine:(stream_engine*)engine;
@ -28,4 +32,3 @@
+ (BOOL)isUsingCronet;
@end
#endif

@ -18,7 +18,8 @@
#import "GRPCCall+Cronet.h"
#ifdef GRPC_COMPILE_WITH_CRONET
const GRPCTransportId gGRPCCoreCronetId = "io.grpc.transport.core.cronet";
static BOOL useCronet = NO;
static stream_engine *globalCronetEngine;
@ -38,4 +39,3 @@ static stream_engine *globalCronetEngine;
}
@end
#endif

@ -17,7 +17,7 @@
*/
#import "GRPCCall+OAuth2.h"
#import "GRPCCall.h"
#import "GRPCCallLegacy.h"
#import <Google/SignIn.h>

@ -16,9 +16,9 @@
*
*/
#import "GRPCCall.h"
#import "GRPCCallLegacy.h"
#import "GRPCCallOptions.h"
@protocol GRPCAuthorizationProtocol;
// Deprecated interface. Please use GRPCCallOptions instead.
@interface GRPCCall (OAuth2)

@ -16,7 +16,7 @@
*
*/
#import "GRPCCall.h"
#import "GRPCCallLegacy.h"
// Deprecated interface. Please use GRPCCallOptions instead.
@interface GRPCCall (Tests)

@ -18,7 +18,7 @@
#import "GRPCCall+Tests.h"
#import "private/GRPCHost.h"
#import "private/GRPCCore/GRPCHost.h"
#import "GRPCCallOptions.h"

@ -33,134 +33,19 @@
*/
#import <Foundation/Foundation.h>
#import <RxLibrary/GRXWriter.h>
#include <AvailabilityMacros.h>
#import "GRPCCallOptions.h"
#import "GRPCDispatchable.h"
#import "GRPCTypes.h"
#include "GRPCCallOptions.h"
// The legacy header is included for backwards compatibility. Some V1 API users are still using
// GRPCCall by importing GRPCCall.h header so we need this import.
#import "GRPCCallLegacy.h"
NS_ASSUME_NONNULL_BEGIN
#pragma mark gRPC errors
/** Domain of NSError objects produced by gRPC. */
extern NSString *const kGRPCErrorDomain;
/**
* gRPC error codes.
* Note that a few of these are never produced by the gRPC libraries, but are of general utility for
* server applications to produce.
*/
typedef NS_ENUM(NSUInteger, GRPCErrorCode) {
/** The operation was cancelled (typically by the caller). */
GRPCErrorCodeCancelled = 1,
/**
* Unknown error. Errors raised by APIs that do not return enough error information may be
* converted to this error.
*/
GRPCErrorCodeUnknown = 2,
/**
* The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION.
* INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the
* server (e.g., a malformed file name).
*/
GRPCErrorCodeInvalidArgument = 3,
/**
* Deadline expired before operation could complete. For operations that change the state of the
* server, this error may be returned even if the operation has completed successfully. For
* example, a successful response from the server could have been delayed long enough for the
* deadline to expire.
*/
GRPCErrorCodeDeadlineExceeded = 4,
/** Some requested entity (e.g., file or directory) was not found. */
GRPCErrorCodeNotFound = 5,
/** Some entity that we attempted to create (e.g., file or directory) already exists. */
GRPCErrorCodeAlreadyExists = 6,
/**
* The caller does not have permission to execute the specified operation. PERMISSION_DENIED isn't
* used for rejections caused by exhausting some resource (RESOURCE_EXHAUSTED is used instead for
* those errors). PERMISSION_DENIED doesn't indicate a failure to identify the caller
* (UNAUTHENTICATED is used instead for those errors).
*/
GRPCErrorCodePermissionDenied = 7,
/**
* The request does not have valid authentication credentials for the operation (e.g. the caller's
* identity can't be verified).
*/
GRPCErrorCodeUnauthenticated = 16,
/** Some resource has been exhausted, perhaps a per-user quota. */
GRPCErrorCodeResourceExhausted = 8,
/**
* The RPC was rejected because the server is not in a state required for the procedure's
* execution. For example, a directory to be deleted may be non-empty, etc.
* The client should not retry until the server state has been explicitly fixed (e.g. by
* performing another RPC). The details depend on the service being called, and should be found in
* the NSError's userInfo.
*/
GRPCErrorCodeFailedPrecondition = 9,
/**
* The RPC was aborted, typically due to a concurrency issue like sequencer check failures,
* transaction aborts, etc. The client should retry at a higher-level (e.g., restarting a read-
* modify-write sequence).
*/
GRPCErrorCodeAborted = 10,
/**
* The RPC was attempted past the valid range. E.g., enumerating past the end of a list.
* Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state
* changes. For example, an RPC to get elements of a list will generate INVALID_ARGUMENT if asked
* to return the element at a negative index, but it will generate OUT_OF_RANGE if asked to return
* the element at an index past the current size of the list.
*/
GRPCErrorCodeOutOfRange = 11,
/** The procedure is not implemented or not supported/enabled in this server. */
GRPCErrorCodeUnimplemented = 12,
/**
* Internal error. Means some invariant expected by the server application or the gRPC library has
* been broken.
*/
GRPCErrorCodeInternal = 13,
/**
* The server is currently unavailable. This is most likely a transient condition and may be
* corrected by retrying with a backoff. Note that it is not always safe to retry
* non-idempotent operations.
*/
GRPCErrorCodeUnavailable = 14,
/** Unrecoverable data loss or corruption. */
GRPCErrorCodeDataLoss = 15,
};
/**
* Keys used in |NSError|'s |userInfo| dictionary to store the response headers and trailers sent by
* the server.
*/
extern NSString *const kGRPCHeadersKey;
extern NSString *const kGRPCTrailersKey;
/** An object can implement this protocol to receive responses from server from a call. */
@protocol GRPCResponseHandler<NSObject>
@required
/**
* All the responses must be issued to a user-provided dispatch queue. This property specifies the
* dispatch queue to be used for issuing the notifications.
*/
@property(atomic, readonly) dispatch_queue_t dispatchQueue;
@protocol GRPCResponseHandler<NSObject, GRPCDispatchable>
@optional
@ -302,114 +187,3 @@ extern NSString *const kGRPCTrailersKey;
@end
NS_ASSUME_NONNULL_END
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability-completeness"
/**
* This interface is deprecated. Please use \a GRPCcall2.
*
* Represents a single gRPC remote call.
*/
@interface GRPCCall : GRXWriter
- (instancetype)init NS_UNAVAILABLE;
/**
* The container of the request headers of an RPC conforms to this protocol, which is a subset of
* NSMutableDictionary's interface. It will become a NSMutableDictionary later on.
* The keys of this container are the header names, which per the HTTP standard are case-
* insensitive. They are stored in lowercase (which is how HTTP/2 mandates them on the wire), and
* can only consist of ASCII characters.
* A header value is a NSString object (with only ASCII characters), unless the header name has the
* suffix "-bin", in which case the value has to be a NSData object.
*/
/**
* These HTTP headers will be passed to the server as part of this call. Each HTTP header is a
* name-value pair with string names and either string or binary values.
*
* The passed dictionary has to use NSString keys, corresponding to the header names. The value
* associated to each can be a NSString object or a NSData object. E.g.:
*
* call.requestHeaders = @{@"authorization": @"Bearer ..."};
*
* call.requestHeaders[@"my-header-bin"] = someData;
*
* After the call is started, trying to modify this property is an error.
*
* The property is initialized to an empty NSMutableDictionary.
*/
@property(atomic, readonly) NSMutableDictionary *requestHeaders;
/**
* This dictionary is populated with the HTTP headers received from the server. This happens before
* any response message is received from the server. It has the same structure as the request
* headers dictionary: Keys are NSString header names; names ending with the suffix "-bin" have a
* NSData value; the others have a NSString value.
*
* The value of this property is nil until all response headers are received, and will change before
* any of -writeValue: or -writesFinishedWithError: are sent to the writeable.
*/
@property(atomic, readonly) NSDictionary *responseHeaders;
/**
* Same as responseHeaders, but populated with the HTTP trailers received from the server before the
* call finishes.
*
* The value of this property is nil until all response trailers are received, and will change
* before -writesFinishedWithError: is sent to the writeable.
*/
@property(atomic, readonly) NSDictionary *responseTrailers;
/**
* The request writer has to write NSData objects into the provided Writeable. The server will
* receive each of those separately and in order as distinct messages.
* A gRPC call might not complete until the request writer finishes. On the other hand, the request
* finishing doesn't necessarily make the call to finish, as the server might continue sending
* messages to the response side of the call indefinitely (depending on the semantics of the
* specific remote method called).
* To finish a call right away, invoke cancel.
* host parameter should not contain the scheme (http:// or https://), only the name or IP addr
* and the port number, for example @"localhost:5050".
*/
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
requestsWriter:(GRXWriter *)requestWriter;
/**
* Finishes the request side of this call, notifies the server that the RPC should be cancelled, and
* finishes the response side of the call with an error of code CANCELED.
*/
- (void)cancel;
/**
* The following methods are deprecated.
*/
+ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path;
@property(atomic, copy, readwrite) NSString *serverName;
@property NSTimeInterval timeout;
- (void)setResponseDispatchQueue:(dispatch_queue_t)queue;
@end
#pragma mark Backwards compatibiity
/** This protocol is kept for backwards compatibility with existing code. */
DEPRECATED_MSG_ATTRIBUTE("Use NSDictionary or NSMutableDictionary instead.")
@protocol GRPCRequestHeaders<NSObject>
@property(nonatomic, readonly) NSUInteger count;
- (id)objectForKeyedSubscript:(id)key;
- (void)setObject:(id)obj forKeyedSubscript:(id)key;
- (void)removeAllObjects;
- (void)removeObjectForKey:(id)key;
@end
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
/** This is only needed for backwards-compatibility. */
@interface NSMutableDictionary (GRPCRequestHeaders)<GRPCRequestHeaders>
@end
#pragma clang diagnostic pop
#pragma clang diagnostic pop

@ -17,56 +17,86 @@
*/
#import "GRPCCall.h"
#import "GRPCCall+Interceptor.h"
#import "GRPCCall+OAuth2.h"
#import "GRPCCallOptions.h"
#import "GRPCInterceptor.h"
#import <RxLibrary/GRXBufferedPipe.h>
#import <RxLibrary/GRXConcurrentWriteable.h>
#import <RxLibrary/GRXImmediateSingleWriter.h>
#import <RxLibrary/GRXWriter+Immediate.h>
#include <grpc/grpc.h>
#include <grpc/support/time.h>
#import "private/GRPCCall+V2API.h"
#import "private/GRPCCallInternal.h"
#import "private/GRPCChannelPool.h"
#import "private/GRPCCompletionQueue.h"
#import "private/GRPCHost.h"
#import "private/GRPCRequestHeaders.h"
#import "private/GRPCWrappedCall.h"
#import "private/NSData+GRPC.h"
#import "private/NSDictionary+GRPC.h"
#import "private/NSError+GRPC.h"
// At most 6 ops can be in an op batch for a client: SEND_INITIAL_METADATA,
// SEND_MESSAGE, SEND_CLOSE_FROM_CLIENT, RECV_INITIAL_METADATA, RECV_MESSAGE,
// and RECV_STATUS_ON_CLIENT.
NSInteger kMaxClientBatch = 6;
#import "private/GRPCTransport+Private.h"
NSString *const kGRPCHeadersKey = @"io.grpc.HeadersKey";
NSString *const kGRPCTrailersKey = @"io.grpc.TrailersKey";
static NSMutableDictionary *callFlags;
static NSString *const kAuthorizationHeader = @"authorization";
static NSString *const kBearerPrefix = @"Bearer ";
NSString *const kGRPCErrorDomain = @"io.grpc";
/**
* The response dispatcher creates its own serial dispatch queue and target the queue to the
* dispatch queue of a user provided response handler. It removes the requirement of having to use
* serial dispatch queue in the user provided response handler.
*/
@interface GRPCResponseDispatcher : NSObject<GRPCResponseHandler>
- (nullable instancetype)initWithResponseHandler:(id<GRPCResponseHandler>)responseHandler;
@end
const char *kCFStreamVarName = "grpc_cfstream";
@implementation GRPCResponseDispatcher {
id<GRPCResponseHandler> _responseHandler;
dispatch_queue_t _dispatchQueue;
}
@interface GRPCCall ()<GRXWriteable>
// Make them read-write.
@property(atomic, strong) NSDictionary *responseHeaders;
@property(atomic, strong) NSDictionary *responseTrailers;
- (instancetype)initWithResponseHandler:(id<GRPCResponseHandler>)responseHandler {
if ((self = [super init])) {
_responseHandler = responseHandler;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 || __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
if (@available(iOS 8.0, macOS 10.10, *)) {
_dispatchQueue = dispatch_queue_create(
NULL,
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0));
} else {
#else
{
#endif
_dispatchQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
}
dispatch_set_target_queue(_dispatchQueue, _responseHandler.dispatchQueue);
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages;
return self;
}
- (dispatch_queue_t)dispatchQueue {
return _dispatchQueue;
}
- (void)didReceiveInitialMetadata:(nullable NSDictionary *)initialMetadata {
if ([_responseHandler respondsToSelector:@selector(didReceiveInitialMetadata:)]) {
[_responseHandler didReceiveInitialMetadata:initialMetadata];
}
}
- (void)didReceiveData:(id)data {
// For backwards compatibility with didReceiveRawMessage, if the user provided a response handler
// that handles didReceiveRawMesssage, we issue to that method instead
if ([_responseHandler respondsToSelector:@selector(didReceiveRawMessage:)]) {
[_responseHandler didReceiveRawMessage:data];
} else if ([_responseHandler respondsToSelector:@selector(didReceiveData:)]) {
[_responseHandler didReceiveData:data];
}
}
- (void)didCloseWithTrailingMetadata:(nullable NSDictionary *)trailingMetadata
error:(nullable NSError *)error {
if ([_responseHandler respondsToSelector:@selector(didCloseWithTrailingMetadata:error:)]) {
[_responseHandler didCloseWithTrailingMetadata:trailingMetadata error:error];
}
}
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
callSafety:(GRPCCallSafety)safety
requestsWriter:(GRXWriter *)requestsWriter
callOptions:(GRPCCallOptions *)callOptions
writeDone:(void (^)(void))writeDone;
- (void)didWriteData {
if ([_responseHandler respondsToSelector:@selector(didWriteData)]) {
[_responseHandler didWriteData];
}
}
@end
@ -140,54 +170,39 @@ const char *kCFStreamVarName = "grpc_cfstream";
}
_responseHandler = responseHandler;
// Initialize the interceptor chain
// First initialize the internal call
GRPCCall2Internal *internalCall = [[GRPCCall2Internal alloc] init];
id<GRPCInterceptorInterface> nextInterceptor = internalCall;
GRPCInterceptorManager *nextManager = nil;
// Then initialize the global interceptor, if applicable
GRPCResponseDispatcher *dispatcher =
[[GRPCResponseDispatcher alloc] initWithResponseHandler:_responseHandler];
NSMutableArray<id<GRPCInterceptorFactory>> *interceptorFactories;
if (_actualCallOptions.interceptorFactories != nil) {
interceptorFactories =
[NSMutableArray arrayWithArray:_actualCallOptions.interceptorFactories];
} else {
interceptorFactories = [NSMutableArray array];
}
id<GRPCInterceptorFactory> globalInterceptorFactory = [GRPCCall2 globalInterceptorFactory];
if (globalInterceptorFactory) {
GRPCInterceptorManager *manager =
[[GRPCInterceptorManager alloc] initWithNextInterceptor:nextInterceptor];
GRPCInterceptor *interceptor =
[globalInterceptorFactory createInterceptorWithManager:manager];
if (interceptor != nil) {
[internalCall setResponseHandler:interceptor];
nextInterceptor = interceptor;
nextManager = manager;
}
if (globalInterceptorFactory != nil) {
[interceptorFactories addObject:globalInterceptorFactory];
}
// Finally initialize the interceptors in the chain
NSArray *interceptorFactories = _actualCallOptions.interceptorFactories;
for (int i = (int)interceptorFactories.count - 1; i >= 0; i--) {
GRPCInterceptorManager *manager =
[[GRPCInterceptorManager alloc] initWithNextInterceptor:nextInterceptor];
GRPCInterceptor *interceptor = [interceptorFactories[i] createInterceptorWithManager:manager];
NSAssert(interceptor != nil, @"Failed to create interceptor from factory: %@",
interceptorFactories[i]);
if (interceptor == nil) {
NSLog(@"Failed to create interceptor from factory: %@", interceptorFactories[i]);
continue;
}
if (nextManager == nil) {
[internalCall setResponseHandler:interceptor];
// continuously create interceptor until one is successfully created
while (_firstInterceptor == nil) {
if (interceptorFactories.count == 0) {
_firstInterceptor = [[GRPCTransportManager alloc] initWithTransportId:_callOptions.transport
previousInterceptor:dispatcher];
break;
} else {
[nextManager setPreviousInterceptor:interceptor];
_firstInterceptor =
[[GRPCInterceptorManager alloc] initWithFactories:interceptorFactories
previousInterceptor:dispatcher
transportId:_callOptions.transport];
if (_firstInterceptor == nil) {
[interceptorFactories removeObjectAtIndex:0];
}
}
nextInterceptor = interceptor;
nextManager = manager;
}
if (nextManager == nil) {
[internalCall setResponseHandler:_responseHandler];
} else {
[nextManager setPreviousInterceptor:_responseHandler];
NSAssert(_firstInterceptor != nil, @"Failed to create interceptor or transport.");
if (_firstInterceptor == nil) {
NSLog(@"Failed to create interceptor or transport.");
}
_firstInterceptor = nextInterceptor;
}
return self;
@ -200,696 +215,42 @@ const char *kCFStreamVarName = "grpc_cfstream";
}
- (void)start {
id<GRPCInterceptorInterface> copiedFirstInterceptor;
@synchronized(self) {
copiedFirstInterceptor = _firstInterceptor;
}
GRPCRequestOptions *requestOptions = [_requestOptions copy];
GRPCCallOptions *callOptions = [_actualCallOptions copy];
if ([copiedFirstInterceptor respondsToSelector:@selector(startWithRequestOptions:callOptions:)]) {
dispatch_async(copiedFirstInterceptor.requestDispatchQueue, ^{
[copiedFirstInterceptor startWithRequestOptions:requestOptions callOptions:callOptions];
});
}
id<GRPCInterceptorInterface> copiedFirstInterceptor = _firstInterceptor;
GRPCRequestOptions *requestOptions = _requestOptions;
GRPCCallOptions *callOptions = _actualCallOptions;
dispatch_async(copiedFirstInterceptor.dispatchQueue, ^{
[copiedFirstInterceptor startWithRequestOptions:requestOptions callOptions:callOptions];
});
}
- (void)cancel {
id<GRPCInterceptorInterface> copiedFirstInterceptor;
@synchronized(self) {
copiedFirstInterceptor = _firstInterceptor;
}
if ([copiedFirstInterceptor respondsToSelector:@selector(cancel)]) {
dispatch_async(copiedFirstInterceptor.requestDispatchQueue, ^{
id<GRPCInterceptorInterface> copiedFirstInterceptor = _firstInterceptor;
if (copiedFirstInterceptor != nil) {
dispatch_async(copiedFirstInterceptor.dispatchQueue, ^{
[copiedFirstInterceptor cancel];
});
}
}
- (void)writeData:(id)data {
id<GRPCInterceptorInterface> copiedFirstInterceptor;
@synchronized(self) {
copiedFirstInterceptor = _firstInterceptor;
}
if ([copiedFirstInterceptor respondsToSelector:@selector(writeData:)]) {
dispatch_async(copiedFirstInterceptor.requestDispatchQueue, ^{
[copiedFirstInterceptor writeData:data];
});
}
}
- (void)finish {
id<GRPCInterceptorInterface> copiedFirstInterceptor;
@synchronized(self) {
copiedFirstInterceptor = _firstInterceptor;
}
if ([copiedFirstInterceptor respondsToSelector:@selector(finish)]) {
dispatch_async(copiedFirstInterceptor.requestDispatchQueue, ^{
[copiedFirstInterceptor finish];
});
}
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages {
id<GRPCInterceptorInterface> copiedFirstInterceptor;
@synchronized(self) {
copiedFirstInterceptor = _firstInterceptor;
}
if ([copiedFirstInterceptor respondsToSelector:@selector(receiveNextMessages:)]) {
dispatch_async(copiedFirstInterceptor.requestDispatchQueue, ^{
[copiedFirstInterceptor receiveNextMessages:numberOfMessages];
});
}
}
@end
// The following methods of a C gRPC call object aren't reentrant, and thus
// calls to them must be serialized:
// - start_batch
// - destroy
//
// start_batch with a SEND_MESSAGE argument can only be called after the
// OP_COMPLETE event for any previous write is received. This is achieved by
// pausing the requests writer immediately every time it writes a value, and
// resuming it again when OP_COMPLETE is received.
//
// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
// the OP_COMPLETE event for any previous read is received.This is easier to
// enforce, as we're writing the received messages into the writeable:
// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
// each RECV_MESSAGE batch.
@implementation GRPCCall {
dispatch_queue_t _callQueue;
NSString *_host;
NSString *_path;
GRPCCallSafety _callSafety;
GRPCCallOptions *_callOptions;
GRPCWrappedCall *_wrappedCall;
// The C gRPC library has less guarantees on the ordering of events than we
// do. Particularly, in the face of errors, there's no ordering guarantee at
// all. This wrapper over our actual writeable ensures thread-safety and
// correct ordering.
GRXConcurrentWriteable *_responseWriteable;
// The network thread wants the requestWriter to resume (when the server is ready for more input),
// or to stop (on errors), concurrently with user threads that want to start it, pause it or stop
// it. Because a writer isn't thread-safe, we'll synchronize those operations on it.
// We don't use a dispatch queue for that purpose, because the writer can call writeValue: or
// writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to
// pause the writer immediately on writeValue:, so we need our locking to be recursive.
GRXWriter *_requestWriter;
// To create a retain cycle when a call is started, up until it finishes. See
// |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a
// reference to the call object if all they're interested in is the handler being executed when
// the response arrives.
GRPCCall *_retainSelf;
GRPCRequestHeaders *_requestHeaders;
// In the case that the call is a unary call (i.e. the writer to GRPCCall is of type
// GRXImmediateSingleWriter), GRPCCall will delay sending ops (not send them to C core
// immediately) and buffer them into a batch _unaryOpBatch. The batch is sent to C core when
// the SendClose op is added.
BOOL _unaryCall;
NSMutableArray *_unaryOpBatch;
// The dispatch queue to be used for enqueuing responses to user. Defaulted to the main dispatch
// queue
dispatch_queue_t _responseQueue;
// The OAuth2 token fetched from a token provider.
NSString *_fetchedOauth2AccessToken;
// The callback to be called when a write message op is done.
void (^_writeDone)(void);
// Indicate a read request to core is pending.
BOOL _pendingCoreRead;
// Indicate pending read message request from user.
NSUInteger _pendingReceiveNextMessages;
}
@synthesize state = _state;
+ (void)initialize {
// Guarantees the code in {} block is invoked only once. See ref at:
// https://developer.apple.com/documentation/objectivec/nsobject/1418639-initialize?language=objc
if (self == [GRPCCall self]) {
grpc_init();
callFlags = [NSMutableDictionary dictionary];
}
}
+ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path {
if (host.length == 0 || path.length == 0) {
return;
}
NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
@synchronized(callFlags) {
switch (callSafety) {
case GRPCCallSafetyDefault:
callFlags[hostAndPath] = @0;
break;
case GRPCCallSafetyIdempotentRequest:
callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
break;
case GRPCCallSafetyCacheableRequest:
callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
break;
default:
break;
}
}
}
+ (uint32_t)callFlagsForHost:(NSString *)host path:(NSString *)path {
NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
@synchronized(callFlags) {
return [callFlags[hostAndPath] intValue];
}
}
// Designated initializer
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
requestsWriter:(GRXWriter *)requestWriter {
return [self initWithHost:host
path:path
callSafety:GRPCCallSafetyDefault
requestsWriter:requestWriter
callOptions:nil];
}
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
callSafety:(GRPCCallSafety)safety
requestsWriter:(GRXWriter *)requestsWriter
callOptions:(GRPCCallOptions *)callOptions {
return [self initWithHost:host
path:path
callSafety:safety
requestsWriter:requestsWriter
callOptions:callOptions
writeDone:nil];
}
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
callSafety:(GRPCCallSafety)safety
requestsWriter:(GRXWriter *)requestsWriter
callOptions:(GRPCCallOptions *)callOptions
writeDone:(void (^)(void))writeDone {
// Purposely using pointer rather than length (host.length == 0) for backwards compatibility.
NSAssert(host != nil && path != nil, @"Neither host nor path can be nil.");
NSAssert(safety <= GRPCCallSafetyCacheableRequest, @"Invalid call safety value.");
NSAssert(requestsWriter.state == GRXWriterStateNotStarted,
@"The requests writer can't be already started.");
if (!host || !path) {
return nil;
}
if (safety > GRPCCallSafetyCacheableRequest) {
return nil;
}
if (requestsWriter.state != GRXWriterStateNotStarted) {
return nil;
}
if ((self = [super init])) {
_host = [host copy];
_path = [path copy];
_callSafety = safety;
_callOptions = [callOptions copy];
// Serial queue to invoke the non-reentrant methods of the grpc_call object.
_callQueue = dispatch_queue_create("io.grpc.call", DISPATCH_QUEUE_SERIAL);
_requestWriter = requestsWriter;
_requestHeaders = [[GRPCRequestHeaders alloc] initWithCall:self];
_writeDone = writeDone;
if ([requestsWriter isKindOfClass:[GRXImmediateSingleWriter class]]) {
_unaryCall = YES;
_unaryOpBatch = [NSMutableArray arrayWithCapacity:kMaxClientBatch];
}
_responseQueue = dispatch_get_main_queue();
// do not start a read until initial metadata is received
_pendingReceiveNextMessages = 0;
_pendingCoreRead = YES;
}
return self;
}
- (void)setResponseDispatchQueue:(dispatch_queue_t)queue {
@synchronized(self) {
if (_state != GRXWriterStateNotStarted) {
return;
}
_responseQueue = queue;
}
}
#pragma mark Finish
// This function should support being called within a @synchronized(self) block in another function
// Should not manipulate _requestWriter for deadlock prevention.
- (void)finishWithError:(NSError *)errorOrNil {
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
_state = GRXWriterStateFinished;
if (errorOrNil) {
[_responseWriteable cancelWithError:errorOrNil];
} else {
[_responseWriteable enqueueSuccessfulCompletion];
}
// If the call isn't retained anywhere else, it can be deallocated now.
_retainSelf = nil;
}
}
- (void)cancel {
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
[self finishWithError:[NSError
errorWithDomain:kGRPCErrorDomain
code:GRPCErrorCodeCancelled
userInfo:@{NSLocalizedDescriptionKey : @"Canceled by app"}]];
[_wrappedCall cancel];
}
_requestWriter.state = GRXWriterStateFinished;
}
- (void)dealloc {
__block GRPCWrappedCall *wrappedCall = _wrappedCall;
dispatch_async(_callQueue, ^{
wrappedCall = nil;
});
}
#pragma mark Read messages
// Only called from the call queue.
// The handler will be called from the network queue.
- (void)startReadWithHandler:(void (^)(grpc_byte_buffer *))handler {
// TODO(jcanizales): Add error handlers for async failures
[_wrappedCall startBatchWithOperations:@[ [[GRPCOpRecvMessage alloc] initWithHandler:handler] ]];
}
// Called initially from the network queue once response headers are received,
// then "recursively" from the responseWriteable queue after each response from the
// server has been written.
// If the call is currently paused, this is a noop. Restarting the call will invoke this
// method.
// TODO(jcanizales): Rename to readResponseIfNotPaused.
- (void)maybeStartNextRead {
@synchronized(self) {
if (_state != GRXWriterStateStarted) {
return;
}
if (_callOptions.flowControlEnabled && (_pendingCoreRead || _pendingReceiveNextMessages == 0)) {
return;
}
_pendingCoreRead = YES;
_pendingReceiveNextMessages--;
}
dispatch_async(_callQueue, ^{
__weak GRPCCall *weakSelf = self;
[self startReadWithHandler:^(grpc_byte_buffer *message) {
if (message == NULL) {
// No more messages from the server
return;
}
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf == nil) {
grpc_byte_buffer_destroy(message);
return;
}
NSData *data = [NSData grpc_dataWithByteBuffer:message];
grpc_byte_buffer_destroy(message);
if (!data) {
// The app doesn't have enough memory to hold the server response. We
// don't want to throw, because the app shouldn't crash for a behavior
// that's on the hands of any server to have. Instead we finish and ask
// the server to cancel.
@synchronized(strongSelf) {
strongSelf->_pendingCoreRead = NO;
[strongSelf
finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
code:GRPCErrorCodeResourceExhausted
userInfo:@{
NSLocalizedDescriptionKey :
@"Client does not have enough memory to "
@"hold the server response."
}]];
[strongSelf->_wrappedCall cancel];
}
strongSelf->_requestWriter.state = GRXWriterStateFinished;
} else {
@synchronized(strongSelf) {
[strongSelf->_responseWriteable enqueueValue:data
completionHandler:^{
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
@synchronized(strongSelf) {
strongSelf->_pendingCoreRead = NO;
[strongSelf maybeStartNextRead];
}
}
}];
}
}
}];
id<GRPCInterceptorInterface> copiedFirstInterceptor = _firstInterceptor;
dispatch_async(copiedFirstInterceptor.dispatchQueue, ^{
[copiedFirstInterceptor writeData:data];
});
}
#pragma mark Send headers
- (void)sendHeaders {
// TODO (mxyan): Remove after deprecated methods are removed
uint32_t callSafetyFlags = 0;
switch (_callSafety) {
case GRPCCallSafetyDefault:
callSafetyFlags = 0;
break;
case GRPCCallSafetyIdempotentRequest:
callSafetyFlags = GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
break;
case GRPCCallSafetyCacheableRequest:
callSafetyFlags = GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
break;
}
NSMutableDictionary *headers = [_requestHeaders mutableCopy];
NSString *fetchedOauth2AccessToken;
@synchronized(self) {
fetchedOauth2AccessToken = _fetchedOauth2AccessToken;
}
if (fetchedOauth2AccessToken != nil) {
headers[@"authorization"] = [kBearerPrefix stringByAppendingString:fetchedOauth2AccessToken];
} else if (_callOptions.oauth2AccessToken != nil) {
headers[@"authorization"] =
[kBearerPrefix stringByAppendingString:_callOptions.oauth2AccessToken];
}
// TODO(jcanizales): Add error handlers for async failures
GRPCOpSendMetadata *op = [[GRPCOpSendMetadata alloc]
initWithMetadata:headers
flags:callSafetyFlags
handler:nil]; // No clean-up needed after SEND_INITIAL_METADATA
dispatch_async(_callQueue, ^{
if (!self->_unaryCall) {
[self->_wrappedCall startBatchWithOperations:@[ op ]];
} else {
[self->_unaryOpBatch addObject:op];
}
- (void)finish {
id<GRPCInterceptorInterface> copiedFirstInterceptor = _firstInterceptor;
dispatch_async(copiedFirstInterceptor.dispatchQueue, ^{
[copiedFirstInterceptor finish];
});
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages {
if (numberOfMessages == 0) {
return;
}
@synchronized(self) {
_pendingReceiveNextMessages += numberOfMessages;
if (_state != GRXWriterStateStarted || !_callOptions.flowControlEnabled) {
return;
}
[self maybeStartNextRead];
}
}
#pragma mark GRXWriteable implementation
// Only called from the call queue. The error handler will be called from the
// network queue if the write didn't succeed.
// If the call is a unary call, parameter \a errorHandler will be ignored and
// the error handler of GRPCOpSendClose will be executed in case of error.
- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)(void))errorHandler {
__weak GRPCCall *weakSelf = self;
void (^resumingHandler)(void) = ^{
// Resume the request writer.
GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
strongSelf->_requestWriter.state = GRXWriterStateStarted;
if (strongSelf->_writeDone) {
strongSelf->_writeDone();
}
}
};
GRPCOpSendMessage *op =
[[GRPCOpSendMessage alloc] initWithMessage:message handler:resumingHandler];
if (!_unaryCall) {
[_wrappedCall startBatchWithOperations:@[ op ] errorHandler:errorHandler];
} else {
// Ignored errorHandler since it is the same as the one for GRPCOpSendClose.
// TODO (mxyan): unify the error handlers of all Ops into a single closure.
[_unaryOpBatch addObject:op];
}
}
- (void)writeValue:(id)value {
NSAssert([value isKindOfClass:[NSData class]], @"value must be of type NSData");
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
}
// Pause the input and only resume it when the C layer notifies us that writes
// can proceed.
_requestWriter.state = GRXWriterStatePaused;
dispatch_async(_callQueue, ^{
// Write error is not processed here. It is handled by op batch of GRPC_OP_RECV_STATUS_ON_CLIENT
[self writeMessage:value withErrorHandler:nil];
});
}
// Only called from the call queue. The error handler will be called from the
// network queue if the requests stream couldn't be closed successfully.
- (void)finishRequestWithErrorHandler:(void (^)(void))errorHandler {
if (!_unaryCall) {
[_wrappedCall startBatchWithOperations:@[ [[GRPCOpSendClose alloc] init] ]
errorHandler:errorHandler];
} else {
[_unaryOpBatch addObject:[[GRPCOpSendClose alloc] init]];
[_wrappedCall startBatchWithOperations:_unaryOpBatch errorHandler:errorHandler];
}
}
- (void)writesFinishedWithError:(NSError *)errorOrNil {
if (errorOrNil) {
[self cancel];
} else {
dispatch_async(_callQueue, ^{
// EOS error is not processed here. It is handled by op batch of GRPC_OP_RECV_STATUS_ON_CLIENT
[self finishRequestWithErrorHandler:nil];
});
}
}
#pragma mark Invoke
// Both handlers will eventually be called, from the network queue. Writes can start immediately
// after this.
// The first one (headersHandler), when the response headers are received.
// The second one (completionHandler), whenever the RPC finishes for any reason.
- (void)invokeCallWithHeadersHandler:(void (^)(NSDictionary *))headersHandler
completionHandler:(void (^)(NSError *, NSDictionary *))completionHandler {
dispatch_async(_callQueue, ^{
// TODO(jcanizales): Add error handlers for async failures
[self->_wrappedCall
startBatchWithOperations:@[ [[GRPCOpRecvMetadata alloc] initWithHandler:headersHandler] ]];
[self->_wrappedCall
startBatchWithOperations:@[ [[GRPCOpRecvStatus alloc] initWithHandler:completionHandler] ]];
id<GRPCInterceptorInterface> copiedFirstInterceptor = _firstInterceptor;
dispatch_async(copiedFirstInterceptor.dispatchQueue, ^{
[copiedFirstInterceptor receiveNextMessages:numberOfMessages];
});
}
- (void)invokeCall {
__weak GRPCCall *weakSelf = self;
[self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
// Response headers received.
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
@synchronized(strongSelf) {
// it is ok to set nil because headers are only received once
strongSelf.responseHeaders = nil;
// copy the header so that the GRPCOpRecvMetadata object may be dealloc'ed
NSDictionary *copiedHeaders =
[[NSDictionary alloc] initWithDictionary:headers copyItems:YES];
strongSelf.responseHeaders = copiedHeaders;
strongSelf->_pendingCoreRead = NO;
[strongSelf maybeStartNextRead];
}
}
}
completionHandler:^(NSError *error, NSDictionary *trailers) {
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
strongSelf.responseTrailers = trailers;
if (error) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (error.userInfo) {
[userInfo addEntriesFromDictionary:error.userInfo];
}
userInfo[kGRPCTrailersKey] = strongSelf.responseTrailers;
// Since gRPC core does not guarantee the headers block being called before this block,
// responseHeaders might be nil.
userInfo[kGRPCHeadersKey] = strongSelf.responseHeaders;
error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
}
[strongSelf finishWithError:error];
strongSelf->_requestWriter.state = GRXWriterStateFinished;
}
}];
}
#pragma mark GRXWriter implementation
// Lock acquired inside startWithWriteable:
- (void)startCallWithWriteable:(id<GRXWriteable>)writeable {
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
_responseWriteable =
[[GRXConcurrentWriteable alloc] initWithWriteable:writeable dispatchQueue:_responseQueue];
GRPCPooledChannel *channel =
[[GRPCChannelPool sharedInstance] channelWithHost:_host callOptions:_callOptions];
_wrappedCall = [channel wrappedCallWithPath:_path
completionQueue:[GRPCCompletionQueue completionQueue]
callOptions:_callOptions];
if (_wrappedCall == nil) {
[self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
code:GRPCErrorCodeUnavailable
userInfo:@{
NSLocalizedDescriptionKey :
@"Failed to create call or channel."
}]];
return;
}
[self sendHeaders];
[self invokeCall];
}
// Now that the RPC has been initiated, request writes can start.
[_requestWriter startWithWriteable:self];
}
- (void)startWithWriteable:(id<GRXWriteable>)writeable {
id<GRPCAuthorizationProtocol> tokenProvider = nil;
@synchronized(self) {
_state = GRXWriterStateStarted;
// Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled).
// This makes RPCs in which the call isn't externally retained possible (as long as it is
// started before being autoreleased). Care is taken not to retain self strongly in any of the
// blocks used in this implementation, so that the life of the instance is determined by this
// retain cycle.
_retainSelf = self;
if (_callOptions == nil) {
GRPCMutableCallOptions *callOptions = [[GRPCHost callOptionsForHost:_host] mutableCopy];
if (_serverName.length != 0) {
callOptions.serverAuthority = _serverName;
}
if (_timeout > 0) {
callOptions.timeout = _timeout;
}
uint32_t callFlags = [GRPCCall callFlagsForHost:_host path:_path];
if (callFlags != 0) {
if (callFlags == GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST) {
_callSafety = GRPCCallSafetyIdempotentRequest;
} else if (callFlags == GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) {
_callSafety = GRPCCallSafetyCacheableRequest;
}
}
id<GRPCAuthorizationProtocol> tokenProvider = self.tokenProvider;
if (tokenProvider != nil) {
callOptions.authTokenProvider = tokenProvider;
}
_callOptions = callOptions;
}
NSAssert(_callOptions.authTokenProvider == nil || _callOptions.oauth2AccessToken == nil,
@"authTokenProvider and oauth2AccessToken cannot be set at the same time");
tokenProvider = _callOptions.authTokenProvider;
}
if (tokenProvider != nil) {
__weak typeof(self) weakSelf = self;
[tokenProvider getTokenWithHandler:^(NSString *token) {
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf) {
BOOL startCall = NO;
@synchronized(strongSelf) {
if (strongSelf->_state != GRXWriterStateFinished) {
startCall = YES;
if (token) {
strongSelf->_fetchedOauth2AccessToken = [token copy];
}
}
}
if (startCall) {
[strongSelf startCallWithWriteable:writeable];
}
}
}];
} else {
[self startCallWithWriteable:writeable];
}
}
- (void)setState:(GRXWriterState)newState {
@synchronized(self) {
// Manual transitions are only allowed from the started or paused states.
if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
return;
}
switch (newState) {
case GRXWriterStateFinished:
_state = newState;
// Per GRXWriter's contract, setting the state to Finished manually
// means one doesn't wish the writeable to be messaged anymore.
[_responseWriteable cancelSilently];
_responseWriteable = nil;
return;
case GRXWriterStatePaused:
_state = newState;
return;
case GRXWriterStateStarted:
if (_state == GRXWriterStatePaused) {
_state = newState;
[self maybeStartNextRead];
}
return;
case GRXWriterStateNotStarted:
return;
}
}
}
@end

@ -0,0 +1,136 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* This is the legacy interface of this gRPC library. This API is deprecated and users should use
* the API in GRPCCall.h. This API exists solely for the purpose of backwards compatibility.
*/
#import <RxLibrary/GRXWriter.h>
#import "GRPCTypes.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability-completeness"
/**
* This interface is deprecated. Please use \a GRPCCall2.
*
* Represents a single gRPC remote call.
*/
@interface GRPCCall : GRXWriter
- (instancetype)init NS_UNAVAILABLE;
/**
* The container of the request headers of an RPC conforms to this protocol, which is a subset of
* NSMutableDictionary's interface. It will become a NSMutableDictionary later on.
* The keys of this container are the header names, which per the HTTP standard are case-
* insensitive. They are stored in lowercase (which is how HTTP/2 mandates them on the wire), and
* can only consist of ASCII characters.
* A header value is a NSString object (with only ASCII characters), unless the header name has the
* suffix "-bin", in which case the value has to be a NSData object.
*/
/**
* These HTTP headers will be passed to the server as part of this call. Each HTTP header is a
* name-value pair with string names and either string or binary values.
*
* The passed dictionary has to use NSString keys, corresponding to the header names. The value
* associated to each can be a NSString object or a NSData object. E.g.:
*
* call.requestHeaders = @{@"authorization": @"Bearer ..."};
*
* call.requestHeaders[@"my-header-bin"] = someData;
*
* After the call is started, trying to modify this property is an error.
*
* The property is initialized to an empty NSMutableDictionary.
*/
@property(atomic, readonly) NSMutableDictionary *requestHeaders;
/**
* This dictionary is populated with the HTTP headers received from the server. This happens before
* any response message is received from the server. It has the same structure as the request
* headers dictionary: Keys are NSString header names; names ending with the suffix "-bin" have a
* NSData value; the others have a NSString value.
*
* The value of this property is nil until all response headers are received, and will change before
* any of -writeValue: or -writesFinishedWithError: are sent to the writeable.
*/
@property(atomic, readonly) NSDictionary *responseHeaders;
/**
* Same as responseHeaders, but populated with the HTTP trailers received from the server before the
* call finishes.
*
* The value of this property is nil until all response trailers are received, and will change
* before -writesFinishedWithError: is sent to the writeable.
*/
@property(atomic, readonly) NSDictionary *responseTrailers;
/**
* The request writer has to write NSData objects into the provided Writeable. The server will
* receive each of those separately and in order as distinct messages.
* A gRPC call might not complete until the request writer finishes. On the other hand, the request
* finishing doesn't necessarily make the call to finish, as the server might continue sending
* messages to the response side of the call indefinitely (depending on the semantics of the
* specific remote method called).
* To finish a call right away, invoke cancel.
* host parameter should not contain the scheme (http:// or https://), only the name or IP addr
* and the port number, for example @"localhost:5050".
*/
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
requestsWriter:(GRXWriter *)requestWriter;
/**
* Finishes the request side of this call, notifies the server that the RPC should be cancelled, and
* finishes the response side of the call with an error of code CANCELED.
*/
- (void)cancel;
/**
* The following methods are deprecated.
*/
+ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path;
@property(atomic, copy, readwrite) NSString *serverName;
@property NSTimeInterval timeout;
- (void)setResponseDispatchQueue:(dispatch_queue_t)queue;
@end
#pragma mark Backwards compatibiity
/** This protocol is kept for backwards compatibility with existing code. */
DEPRECATED_MSG_ATTRIBUTE("Use NSDictionary or NSMutableDictionary instead.")
@protocol GRPCRequestHeaders<NSObject>
@property(nonatomic, readonly) NSUInteger count;
- (id)objectForKeyedSubscript:(id)key;
- (void)setObject:(id)obj forKeyedSubscript:(id)key;
- (void)removeAllObjects;
- (void)removeObjectForKey:(id)key;
@end
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
/** This is only needed for backwards-compatibility. */
@interface NSMutableDictionary (GRPCRequestHeaders)<GRPCRequestHeaders>
@end
#pragma clang diagnostic pop
#pragma clang diagnostic pop

@ -0,0 +1,677 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "GRPCCallLegacy.h"
#import "GRPCCall+OAuth2.h"
#import "GRPCCallOptions.h"
#import "GRPCTypes.h"
#import "private/GRPCCore/GRPCChannelPool.h"
#import "private/GRPCCore/GRPCCompletionQueue.h"
#import "private/GRPCCore/GRPCHost.h"
#import "private/GRPCCore/GRPCWrappedCall.h"
#import "private/GRPCCore/NSData+GRPC.h"
#import <RxLibrary/GRXBufferedPipe.h>
#import <RxLibrary/GRXConcurrentWriteable.h>
#import <RxLibrary/GRXImmediateSingleWriter.h>
#import <RxLibrary/GRXWriter+Immediate.h>
#include <grpc/grpc.h>
const char *kCFStreamVarName = "grpc_cfstream";
static NSMutableDictionary *callFlags;
// At most 6 ops can be in an op batch for a client: SEND_INITIAL_METADATA,
// SEND_MESSAGE, SEND_CLOSE_FROM_CLIENT, RECV_INITIAL_METADATA, RECV_MESSAGE,
// and RECV_STATUS_ON_CLIENT.
NSInteger kMaxClientBatch = 6;
static NSString *const kAuthorizationHeader = @"authorization";
static NSString *const kBearerPrefix = @"Bearer ";
@interface GRPCCall ()<GRXWriteable>
// Make them read-write.
@property(atomic, strong) NSDictionary *responseHeaders;
@property(atomic, strong) NSDictionary *responseTrailers;
- (void)receiveNextMessages:(NSUInteger)numberOfMessages;
@end
// The following methods of a C gRPC call object aren't reentrant, and thus
// calls to them must be serialized:
// - start_batch
// - destroy
//
// start_batch with a SEND_MESSAGE argument can only be called after the
// OP_COMPLETE event for any previous write is received. This is achieved by
// pausing the requests writer immediately every time it writes a value, and
// resuming it again when OP_COMPLETE is received.
//
// Similarly, start_batch with a RECV_MESSAGE argument can only be called after
// the OP_COMPLETE event for any previous read is received.This is easier to
// enforce, as we're writing the received messages into the writeable:
// start_batch is enqueued once upon receiving the OP_COMPLETE event for the
// RECV_METADATA batch, and then once after receiving each OP_COMPLETE event for
// each RECV_MESSAGE batch.
@implementation GRPCCall {
dispatch_queue_t _callQueue;
NSString *_host;
NSString *_path;
GRPCCallSafety _callSafety;
GRPCCallOptions *_callOptions;
GRPCWrappedCall *_wrappedCall;
// The C gRPC library has less guarantees on the ordering of events than we
// do. Particularly, in the face of errors, there's no ordering guarantee at
// all. This wrapper over our actual writeable ensures thread-safety and
// correct ordering.
GRXConcurrentWriteable *_responseWriteable;
// The network thread wants the requestWriter to resume (when the server is ready for more input),
// or to stop (on errors), concurrently with user threads that want to start it, pause it or stop
// it. Because a writer isn't thread-safe, we'll synchronize those operations on it.
// We don't use a dispatch queue for that purpose, because the writer can call writeValue: or
// writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to
// pause the writer immediately on writeValue:, so we need our locking to be recursive.
GRXWriter *_requestWriter;
// To create a retain cycle when a call is started, up until it finishes. See
// |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a
// reference to the call object if all they're interested in is the handler being executed when
// the response arrives.
GRPCCall *_retainSelf;
GRPCRequestHeaders *_requestHeaders;
// In the case that the call is a unary call (i.e. the writer to GRPCCall is of type
// GRXImmediateSingleWriter), GRPCCall will delay sending ops (not send them to C core
// immediately) and buffer them into a batch _unaryOpBatch. The batch is sent to C core when
// the SendClose op is added.
BOOL _unaryCall;
NSMutableArray *_unaryOpBatch;
// The dispatch queue to be used for enqueuing responses to user. Defaulted to the main dispatch
// queue
dispatch_queue_t _responseQueue;
// The OAuth2 token fetched from a token provider.
NSString *_fetchedOauth2AccessToken;
// The callback to be called when a write message op is done.
void (^_writeDone)(void);
// Indicate a read request to core is pending.
BOOL _pendingCoreRead;
// Indicate pending read message request from user.
NSUInteger _pendingReceiveNextMessages;
}
@synthesize state = _state;
+ (void)initialize {
// Guarantees the code in {} block is invoked only once. See ref at:
// https://developer.apple.com/documentation/objectivec/nsobject/1418639-initialize?language=objc
if (self == [GRPCCall self]) {
grpc_init();
callFlags = [NSMutableDictionary dictionary];
}
}
+ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path {
if (host.length == 0 || path.length == 0) {
return;
}
NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
@synchronized(callFlags) {
switch (callSafety) {
case GRPCCallSafetyDefault:
callFlags[hostAndPath] = @0;
break;
case GRPCCallSafetyIdempotentRequest:
callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
break;
case GRPCCallSafetyCacheableRequest:
callFlags[hostAndPath] = @GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
break;
default:
break;
}
}
}
+ (uint32_t)callFlagsForHost:(NSString *)host path:(NSString *)path {
NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path];
@synchronized(callFlags) {
return [callFlags[hostAndPath] intValue];
}
}
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
requestsWriter:(GRXWriter *)requestWriter {
return [self initWithHost:host
path:path
callSafety:GRPCCallSafetyDefault
requestsWriter:requestWriter
callOptions:nil
writeDone:nil];
}
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
callSafety:(GRPCCallSafety)safety
requestsWriter:(GRXWriter *)requestsWriter
callOptions:(GRPCCallOptions *)callOptions
writeDone:(void (^)(void))writeDone {
// Purposely using pointer rather than length (host.length == 0) for backwards compatibility.
NSAssert(host != nil && path != nil, @"Neither host nor path can be nil.");
NSAssert(safety <= GRPCCallSafetyCacheableRequest, @"Invalid call safety value.");
NSAssert(requestsWriter.state == GRXWriterStateNotStarted,
@"The requests writer can't be already started.");
if (!host || !path) {
return nil;
}
if (safety > GRPCCallSafetyCacheableRequest) {
return nil;
}
if (requestsWriter.state != GRXWriterStateNotStarted) {
return nil;
}
if ((self = [super init])) {
_host = [host copy];
_path = [path copy];
_callSafety = safety;
_callOptions = [callOptions copy];
// Serial queue to invoke the non-reentrant methods of the grpc_call object.
_callQueue = dispatch_queue_create("io.grpc.call", DISPATCH_QUEUE_SERIAL);
_requestWriter = requestsWriter;
_requestHeaders = [[GRPCRequestHeaders alloc] initWithCall:self];
_writeDone = writeDone;
if ([requestsWriter isKindOfClass:[GRXImmediateSingleWriter class]]) {
_unaryCall = YES;
_unaryOpBatch = [NSMutableArray arrayWithCapacity:kMaxClientBatch];
}
_responseQueue = dispatch_get_main_queue();
// do not start a read until initial metadata is received
_pendingReceiveNextMessages = 0;
_pendingCoreRead = YES;
}
return self;
}
- (void)setResponseDispatchQueue:(dispatch_queue_t)queue {
@synchronized(self) {
if (_state != GRXWriterStateNotStarted) {
return;
}
_responseQueue = queue;
}
}
#pragma mark Finish
// This function should support being called within a @synchronized(self) block in another function
// Should not manipulate _requestWriter for deadlock prevention.
- (void)finishWithError:(NSError *)errorOrNil {
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
_state = GRXWriterStateFinished;
if (errorOrNil) {
[_responseWriteable cancelWithError:errorOrNil];
} else {
[_responseWriteable enqueueSuccessfulCompletion];
}
// If the call isn't retained anywhere else, it can be deallocated now.
_retainSelf = nil;
}
}
- (void)cancel {
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
[self finishWithError:[NSError
errorWithDomain:kGRPCErrorDomain
code:GRPCErrorCodeCancelled
userInfo:@{NSLocalizedDescriptionKey : @"Canceled by app"}]];
[_wrappedCall cancel];
}
_requestWriter.state = GRXWriterStateFinished;
}
- (void)dealloc {
__block GRPCWrappedCall *wrappedCall = _wrappedCall;
dispatch_async(_callQueue, ^{
wrappedCall = nil;
});
}
#pragma mark Read messages
// Only called from the call queue.
// The handler will be called from the network queue.
- (void)startReadWithHandler:(void (^)(grpc_byte_buffer *))handler {
// TODO(jcanizales): Add error handlers for async failures
[_wrappedCall startBatchWithOperations:@[ [[GRPCOpRecvMessage alloc] initWithHandler:handler] ]];
}
// Called initially from the network queue once response headers are received,
// then "recursively" from the responseWriteable queue after each response from the
// server has been written.
// If the call is currently paused, this is a noop. Restarting the call will invoke this
// method.
// TODO(jcanizales): Rename to readResponseIfNotPaused.
- (void)maybeStartNextRead {
@synchronized(self) {
if (_state != GRXWriterStateStarted) {
return;
}
if (_callOptions.flowControlEnabled && (_pendingCoreRead || _pendingReceiveNextMessages == 0)) {
return;
}
_pendingCoreRead = YES;
_pendingReceiveNextMessages--;
}
dispatch_async(_callQueue, ^{
__weak GRPCCall *weakSelf = self;
[self startReadWithHandler:^(grpc_byte_buffer *message) {
if (message == NULL) {
// No more messages from the server
return;
}
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf == nil) {
grpc_byte_buffer_destroy(message);
return;
}
NSData *data = [NSData grpc_dataWithByteBuffer:message];
grpc_byte_buffer_destroy(message);
if (!data) {
// The app doesn't have enough memory to hold the server response. We
// don't want to throw, because the app shouldn't crash for a behavior
// that's on the hands of any server to have. Instead we finish and ask
// the server to cancel.
@synchronized(strongSelf) {
strongSelf->_pendingCoreRead = NO;
[strongSelf
finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
code:GRPCErrorCodeResourceExhausted
userInfo:@{
NSLocalizedDescriptionKey :
@"Client does not have enough memory to "
@"hold the server response."
}]];
[strongSelf->_wrappedCall cancel];
}
strongSelf->_requestWriter.state = GRXWriterStateFinished;
} else {
@synchronized(strongSelf) {
[strongSelf->_responseWriteable enqueueValue:data
completionHandler:^{
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
@synchronized(strongSelf) {
strongSelf->_pendingCoreRead = NO;
[strongSelf maybeStartNextRead];
}
}
}];
}
}
}];
});
}
#pragma mark Send headers
- (void)sendHeaders {
// TODO (mxyan): Remove after deprecated methods are removed
uint32_t callSafetyFlags = 0;
switch (_callSafety) {
case GRPCCallSafetyDefault:
callSafetyFlags = 0;
break;
case GRPCCallSafetyIdempotentRequest:
callSafetyFlags = GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
break;
case GRPCCallSafetyCacheableRequest:
callSafetyFlags = GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
break;
}
NSMutableDictionary *headers = [_requestHeaders mutableCopy];
NSString *fetchedOauth2AccessToken;
@synchronized(self) {
fetchedOauth2AccessToken = _fetchedOauth2AccessToken;
}
if (fetchedOauth2AccessToken != nil) {
headers[@"authorization"] = [kBearerPrefix stringByAppendingString:fetchedOauth2AccessToken];
} else if (_callOptions.oauth2AccessToken != nil) {
headers[@"authorization"] =
[kBearerPrefix stringByAppendingString:_callOptions.oauth2AccessToken];
}
// TODO(jcanizales): Add error handlers for async failures
GRPCOpSendMetadata *op = [[GRPCOpSendMetadata alloc]
initWithMetadata:headers
flags:callSafetyFlags
handler:nil]; // No clean-up needed after SEND_INITIAL_METADATA
dispatch_async(_callQueue, ^{
if (!self->_unaryCall) {
[self->_wrappedCall startBatchWithOperations:@[ op ]];
} else {
[self->_unaryOpBatch addObject:op];
}
});
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages {
if (numberOfMessages == 0) {
return;
}
@synchronized(self) {
_pendingReceiveNextMessages += numberOfMessages;
if (_state != GRXWriterStateStarted || !_callOptions.flowControlEnabled) {
return;
}
[self maybeStartNextRead];
}
}
#pragma mark GRXWriteable implementation
// Only called from the call queue. The error handler will be called from the
// network queue if the write didn't succeed.
// If the call is a unary call, parameter \a errorHandler will be ignored and
// the error handler of GRPCOpSendClose will be executed in case of error.
- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)(void))errorHandler {
__weak GRPCCall *weakSelf = self;
void (^resumingHandler)(void) = ^{
// Resume the request writer.
GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
strongSelf->_requestWriter.state = GRXWriterStateStarted;
if (strongSelf->_writeDone) {
strongSelf->_writeDone();
}
}
};
GRPCOpSendMessage *op =
[[GRPCOpSendMessage alloc] initWithMessage:message handler:resumingHandler];
if (!_unaryCall) {
[_wrappedCall startBatchWithOperations:@[ op ] errorHandler:errorHandler];
} else {
// Ignored errorHandler since it is the same as the one for GRPCOpSendClose.
// TODO (mxyan): unify the error handlers of all Ops into a single closure.
[_unaryOpBatch addObject:op];
}
}
- (void)writeValue:(id)value {
NSAssert([value isKindOfClass:[NSData class]], @"value must be of type NSData");
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
}
// Pause the input and only resume it when the C layer notifies us that writes
// can proceed.
_requestWriter.state = GRXWriterStatePaused;
dispatch_async(_callQueue, ^{
// Write error is not processed here. It is handled by op batch of GRPC_OP_RECV_STATUS_ON_CLIENT
[self writeMessage:value withErrorHandler:nil];
});
}
// Only called from the call queue. The error handler will be called from the
// network queue if the requests stream couldn't be closed successfully.
- (void)finishRequestWithErrorHandler:(void (^)(void))errorHandler {
if (!_unaryCall) {
[_wrappedCall startBatchWithOperations:@[ [[GRPCOpSendClose alloc] init] ]
errorHandler:errorHandler];
} else {
[_unaryOpBatch addObject:[[GRPCOpSendClose alloc] init]];
[_wrappedCall startBatchWithOperations:_unaryOpBatch errorHandler:errorHandler];
}
}
- (void)writesFinishedWithError:(NSError *)errorOrNil {
if (errorOrNil) {
[self cancel];
} else {
dispatch_async(_callQueue, ^{
// EOS error is not processed here. It is handled by op batch of GRPC_OP_RECV_STATUS_ON_CLIENT
[self finishRequestWithErrorHandler:nil];
});
}
}
#pragma mark Invoke
// Both handlers will eventually be called, from the network queue. Writes can start immediately
// after this.
// The first one (headersHandler), when the response headers are received.
// The second one (completionHandler), whenever the RPC finishes for any reason.
- (void)invokeCallWithHeadersHandler:(void (^)(NSDictionary *))headersHandler
completionHandler:(void (^)(NSError *, NSDictionary *))completionHandler {
dispatch_async(_callQueue, ^{
// TODO(jcanizales): Add error handlers for async failures
[self->_wrappedCall
startBatchWithOperations:@[ [[GRPCOpRecvMetadata alloc] initWithHandler:headersHandler] ]];
[self->_wrappedCall
startBatchWithOperations:@[ [[GRPCOpRecvStatus alloc] initWithHandler:completionHandler] ]];
});
}
- (void)invokeCall {
__weak GRPCCall *weakSelf = self;
[self invokeCallWithHeadersHandler:^(NSDictionary *headers) {
// Response headers received.
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
@synchronized(strongSelf) {
// it is ok to set nil because headers are only received once
strongSelf.responseHeaders = nil;
// copy the header so that the GRPCOpRecvMetadata object may be dealloc'ed
NSDictionary *copiedHeaders =
[[NSDictionary alloc] initWithDictionary:headers copyItems:YES];
strongSelf.responseHeaders = copiedHeaders;
strongSelf->_pendingCoreRead = NO;
[strongSelf maybeStartNextRead];
}
}
}
completionHandler:^(NSError *error, NSDictionary *trailers) {
__strong GRPCCall *strongSelf = weakSelf;
if (strongSelf) {
strongSelf.responseTrailers = trailers;
if (error) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (error.userInfo) {
[userInfo addEntriesFromDictionary:error.userInfo];
}
userInfo[kGRPCTrailersKey] = strongSelf.responseTrailers;
// Since gRPC core does not guarantee the headers block being called before this block,
// responseHeaders might be nil.
userInfo[kGRPCHeadersKey] = strongSelf.responseHeaders;
error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
}
[strongSelf finishWithError:error];
strongSelf->_requestWriter.state = GRXWriterStateFinished;
}
}];
}
#pragma mark GRXWriter implementation
// Lock acquired inside startWithWriteable:
- (void)startCallWithWriteable:(id<GRXWriteable>)writeable {
@synchronized(self) {
if (_state == GRXWriterStateFinished) {
return;
}
_responseWriteable =
[[GRXConcurrentWriteable alloc] initWithWriteable:writeable dispatchQueue:_responseQueue];
GRPCPooledChannel *channel =
[[GRPCChannelPool sharedInstance] channelWithHost:_host callOptions:_callOptions];
_wrappedCall = [channel wrappedCallWithPath:_path
completionQueue:[GRPCCompletionQueue completionQueue]
callOptions:_callOptions];
if (_wrappedCall == nil) {
[self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain
code:GRPCErrorCodeUnavailable
userInfo:@{
NSLocalizedDescriptionKey :
@"Failed to create call or channel."
}]];
return;
}
[self sendHeaders];
[self invokeCall];
}
// Now that the RPC has been initiated, request writes can start.
[_requestWriter startWithWriteable:self];
}
- (void)startWithWriteable:(id<GRXWriteable>)writeable {
id<GRPCAuthorizationProtocol> tokenProvider = nil;
@synchronized(self) {
_state = GRXWriterStateStarted;
// Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled).
// This makes RPCs in which the call isn't externally retained possible (as long as it is
// started before being autoreleased). Care is taken not to retain self strongly in any of the
// blocks used in this implementation, so that the life of the instance is determined by this
// retain cycle.
_retainSelf = self;
// If _callOptions is nil, people must be using the deprecated v1 interface. In this case,
// generate the call options from the corresponding GRPCHost configs and apply other options
// that are not covered by GRPCHost.
if (_callOptions == nil) {
GRPCMutableCallOptions *callOptions = [[GRPCHost callOptionsForHost:_host] mutableCopy];
if (_serverName.length != 0) {
callOptions.serverAuthority = _serverName;
}
if (_timeout > 0) {
callOptions.timeout = _timeout;
}
uint32_t callFlags = [GRPCCall callFlagsForHost:_host path:_path];
if (callFlags != 0) {
if (callFlags == GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST) {
_callSafety = GRPCCallSafetyIdempotentRequest;
} else if (callFlags == GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) {
_callSafety = GRPCCallSafetyCacheableRequest;
}
}
id<GRPCAuthorizationProtocol> tokenProvider = self.tokenProvider;
if (tokenProvider != nil) {
callOptions.authTokenProvider = tokenProvider;
}
_callOptions = callOptions;
}
NSAssert(_callOptions.authTokenProvider == nil || _callOptions.oauth2AccessToken == nil,
@"authTokenProvider and oauth2AccessToken cannot be set at the same time");
tokenProvider = _callOptions.authTokenProvider;
}
if (tokenProvider != nil) {
__weak typeof(self) weakSelf = self;
[tokenProvider getTokenWithHandler:^(NSString *token) {
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf) {
BOOL startCall = NO;
@synchronized(strongSelf) {
if (strongSelf->_state != GRXWriterStateFinished) {
startCall = YES;
if (token) {
strongSelf->_fetchedOauth2AccessToken = [token copy];
}
}
}
if (startCall) {
[strongSelf startCallWithWriteable:writeable];
}
}
}];
} else {
[self startCallWithWriteable:writeable];
}
}
- (void)setState:(GRXWriterState)newState {
@synchronized(self) {
// Manual transitions are only allowed from the started or paused states.
if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) {
return;
}
switch (newState) {
case GRXWriterStateFinished:
_state = newState;
// Per GRXWriter's contract, setting the state to Finished manually
// means one doesn't wish the writeable to be messaged anymore.
[_responseWriteable cancelSilently];
_responseWriteable = nil;
return;
case GRXWriterStatePaused:
_state = newState;
return;
case GRXWriterStateStarted:
if (_state == GRXWriterStatePaused) {
_state = newState;
[self maybeStartNextRead];
}
return;
case GRXWriterStateNotStarted:
return;
}
}
}
@end

@ -18,57 +18,11 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Safety remark of a gRPC method as defined in RFC 2616 Section 9.1
*/
typedef NS_ENUM(NSUInteger, GRPCCallSafety) {
/** Signal that there is no guarantees on how the call affects the server state. */
GRPCCallSafetyDefault = 0,
/** Signal that the call is idempotent. gRPC is free to use PUT verb. */
GRPCCallSafetyIdempotentRequest = 1,
/**
* Signal that the call is cacheable and will not affect server state. gRPC is free to use GET
* verb.
*/
GRPCCallSafetyCacheableRequest = 2,
};
// Compression algorithm to be used by a gRPC call
typedef NS_ENUM(NSUInteger, GRPCCompressionAlgorithm) {
GRPCCompressNone = 0,
GRPCCompressDeflate,
GRPCCompressGzip,
GRPCStreamCompressGzip,
};
// GRPCCompressAlgorithm is deprecated; use GRPCCompressionAlgorithm
typedef GRPCCompressionAlgorithm GRPCCompressAlgorithm;
#import "GRPCTypes.h"
/** The transport to be used by a gRPC call */
typedef NS_ENUM(NSUInteger, GRPCTransportType) {
GRPCTransportTypeDefault = 0,
/** gRPC internal HTTP/2 stack with BoringSSL */
GRPCTransportTypeChttp2BoringSSL = 0,
/** Cronet stack */
GRPCTransportTypeCronet,
/** Insecure channel. FOR TEST ONLY! */
GRPCTransportTypeInsecure,
};
/**
* Implement this protocol to provide a token to gRPC when a call is initiated.
*/
@protocol GRPCAuthorizationProtocol
/**
* This method is called when gRPC is about to start the call. When OAuth token is acquired,
* \a handler is expected to be called with \a token being the new token to be used for this call.
*/
- (void)getTokenWithHandler:(void (^)(NSString *_Nullable token))handler;
NS_ASSUME_NONNULL_BEGIN
@end
@protocol GRPCInterceptorFactory;
@interface GRPCCallOptions : NSObject<NSCopying, NSMutableCopying>
@ -104,7 +58,7 @@ typedef NS_ENUM(NSUInteger, GRPCTransportType) {
* this array. This parameter should not be modified by any interceptor and will
* not take effect if done so.
*/
@property(copy, readonly) NSArray *interceptorFactories;
@property(copy, readonly) NSArray<id<GRPCInterceptorFactory>> *interceptorFactories;
// OAuth2 parameters. Users of gRPC may specify one of the following two parameters.
@ -192,10 +146,23 @@ typedef NS_ENUM(NSUInteger, GRPCTransportType) {
@property(copy, readonly, nullable) NSString *PEMCertificateChain;
/**
* Deprecated: this option is deprecated. Please use the property \a transport
* instead.
*
* Select the transport type to be used for this call.
*/
@property(readonly) GRPCTransportType transportType;
/**
* The transport to be used for this call. Users may choose a native transport
* identifier defined in \a GRPCTransport or provided by a non-native transport
* implementation. If the option is left to be NULL, gRPC will use its default
* transport.
*
* This is currently an experimental option.
*/
@property(readonly) GRPCTransportId transport;
/**
* Override the hostname during the TLS hostname validation process.
*/
@ -267,7 +234,7 @@ typedef NS_ENUM(NSUInteger, GRPCTransportType) {
* this array. This parameter should not be modified by any interceptor and will
* not take effect if done so.
*/
@property(copy, readwrite) NSArray *interceptorFactories;
@property(copy, readwrite) NSArray<id<GRPCInterceptorFactory>> *interceptorFactories;
// OAuth2 parameters. Users of gRPC may specify one of the following two parameters.
@ -357,10 +324,23 @@ typedef NS_ENUM(NSUInteger, GRPCTransportType) {
@property(copy, readwrite, nullable) NSString *PEMCertificateChain;
/**
* Deprecated: this option is deprecated. Please use the property \a transport
* instead.
*
* Select the transport type to be used for this call.
*/
@property(readwrite) GRPCTransportType transportType;
/**
* The transport to be used for this call. Users may choose a native transport
* identifier defined in \a GRPCTransport or provided by a non-native ttransport
* implementation. If the option is left to be NULL, gRPC will use its default
* transport.
*
* An interceptor must not change the value of this option.
*/
@property(readwrite) GRPCTransportId transport;
/**
* Override the hostname during the TLS hostname validation process.
*/

@ -17,13 +17,14 @@
*/
#import "GRPCCallOptions.h"
#import "GRPCTransport.h"
#import "internal/GRPCCallOptions+Internal.h"
// The default values for the call options.
static NSString *const kDefaultServerAuthority = nil;
static const NSTimeInterval kDefaultTimeout = 0;
static const BOOL kDefaultFlowControlEnabled = NO;
static NSArray *const kDefaultInterceptorFactories = nil;
static NSArray<id<GRPCInterceptorFactory>> *const kDefaultInterceptorFactories = nil;
static NSDictionary *const kDefaultInitialMetadata = nil;
static NSString *const kDefaultUserAgentPrefix = nil;
static const NSUInteger kDefaultResponseSizeLimit = 0;
@ -41,6 +42,7 @@ static NSString *const kDefaultPEMCertificateChain = nil;
static NSString *const kDefaultOauth2AccessToken = nil;
static const id<GRPCAuthorizationProtocol> kDefaultAuthTokenProvider = nil;
static const GRPCTransportType kDefaultTransportType = GRPCTransportTypeChttp2BoringSSL;
static const GRPCTransportId kDefaultTransport = NULL;
static NSString *const kDefaultHostNameOverride = nil;
static const id kDefaultLogContext = nil;
static NSString *const kDefaultChannelPoolDomain = nil;
@ -62,7 +64,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
NSString *_serverAuthority;
NSTimeInterval _timeout;
BOOL _flowControlEnabled;
NSArray *_interceptorFactories;
NSArray<id<GRPCInterceptorFactory>> *_interceptorFactories;
NSString *_oauth2AccessToken;
id<GRPCAuthorizationProtocol> _authTokenProvider;
NSDictionary *_initialMetadata;
@ -80,6 +82,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
NSString *_PEMPrivateKey;
NSString *_PEMCertificateChain;
GRPCTransportType _transportType;
GRPCTransportId _transport;
NSString *_hostNameOverride;
id<NSObject> _logContext;
NSString *_channelPoolDomain;
@ -107,6 +110,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
@synthesize PEMPrivateKey = _PEMPrivateKey;
@synthesize PEMCertificateChain = _PEMCertificateChain;
@synthesize transportType = _transportType;
@synthesize transport = _transport;
@synthesize hostNameOverride = _hostNameOverride;
@synthesize logContext = _logContext;
@synthesize channelPoolDomain = _channelPoolDomain;
@ -134,6 +138,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
PEMPrivateKey:kDefaultPEMPrivateKey
PEMCertificateChain:kDefaultPEMCertificateChain
transportType:kDefaultTransportType
transport:kDefaultTransport
hostNameOverride:kDefaultHostNameOverride
logContext:kDefaultLogContext
channelPoolDomain:kDefaultChannelPoolDomain
@ -143,7 +148,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
- (instancetype)initWithServerAuthority:(NSString *)serverAuthority
timeout:(NSTimeInterval)timeout
flowControlEnabled:(BOOL)flowControlEnabled
interceptorFactories:(NSArray *)interceptorFactories
interceptorFactories:(NSArray<id<GRPCInterceptorFactory>> *)interceptorFactories
oauth2AccessToken:(NSString *)oauth2AccessToken
authTokenProvider:(id<GRPCAuthorizationProtocol>)authTokenProvider
initialMetadata:(NSDictionary *)initialMetadata
@ -161,6 +166,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
PEMPrivateKey:(NSString *)PEMPrivateKey
PEMCertificateChain:(NSString *)PEMCertificateChain
transportType:(GRPCTransportType)transportType
transport:(GRPCTransportId)transport
hostNameOverride:(NSString *)hostNameOverride
logContext:(id)logContext
channelPoolDomain:(NSString *)channelPoolDomain
@ -193,6 +199,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
_PEMPrivateKey = [PEMPrivateKey copy];
_PEMCertificateChain = [PEMCertificateChain copy];
_transportType = transportType;
_transport = transport;
_hostNameOverride = [hostNameOverride copy];
_logContext = logContext;
_channelPoolDomain = [channelPoolDomain copy];
@ -224,6 +231,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
PEMPrivateKey:_PEMPrivateKey
PEMCertificateChain:_PEMCertificateChain
transportType:_transportType
transport:_transport
hostNameOverride:_hostNameOverride
logContext:_logContext
channelPoolDomain:_channelPoolDomain
@ -256,6 +264,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
PEMPrivateKey:[_PEMPrivateKey copy]
PEMCertificateChain:[_PEMCertificateChain copy]
transportType:_transportType
transport:_transport
hostNameOverride:[_hostNameOverride copy]
logContext:_logContext
channelPoolDomain:[_channelPoolDomain copy]
@ -280,6 +289,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
if (!areObjectsEqual(callOptions.PEMCertificateChain, _PEMCertificateChain)) return NO;
if (!areObjectsEqual(callOptions.hostNameOverride, _hostNameOverride)) return NO;
if (!(callOptions.transportType == _transportType)) return NO;
if (!(TransportIdIsEqual(callOptions.transport, _transport))) return NO;
if (!areObjectsEqual(callOptions.logContext, _logContext)) return NO;
if (!areObjectsEqual(callOptions.channelPoolDomain, _channelPoolDomain)) return NO;
if (!(callOptions.channelID == _channelID)) return NO;
@ -304,6 +314,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
result ^= _PEMCertificateChain.hash;
result ^= _hostNameOverride.hash;
result ^= _transportType;
result ^= TransportIdHash(_transport);
result ^= _logContext.hash;
result ^= _channelPoolDomain.hash;
result ^= _channelID;
@ -336,6 +347,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
@dynamic PEMPrivateKey;
@dynamic PEMCertificateChain;
@dynamic transportType;
@dynamic transport;
@dynamic hostNameOverride;
@dynamic logContext;
@dynamic channelPoolDomain;
@ -363,6 +375,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
PEMPrivateKey:kDefaultPEMPrivateKey
PEMCertificateChain:kDefaultPEMCertificateChain
transportType:kDefaultTransportType
transport:kDefaultTransport
hostNameOverride:kDefaultHostNameOverride
logContext:kDefaultLogContext
channelPoolDomain:kDefaultChannelPoolDomain
@ -392,6 +405,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
PEMPrivateKey:_PEMPrivateKey
PEMCertificateChain:_PEMCertificateChain
transportType:_transportType
transport:_transport
hostNameOverride:_hostNameOverride
logContext:_logContext
channelPoolDomain:_channelPoolDomain
@ -422,6 +436,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
PEMPrivateKey:_PEMPrivateKey
PEMCertificateChain:_PEMCertificateChain
transportType:_transportType
transport:_transport
hostNameOverride:_hostNameOverride
logContext:_logContext
channelPoolDomain:_channelPoolDomain
@ -445,7 +460,7 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
_flowControlEnabled = flowControlEnabled;
}
- (void)setInterceptorFactories:(NSArray *)interceptorFactories {
- (void)setInterceptorFactories:(NSArray<id<GRPCInterceptorFactory>> *)interceptorFactories {
_interceptorFactories = interceptorFactories;
}
@ -538,6 +553,10 @@ static BOOL areObjectsEqual(id obj1, id obj2) {
_transportType = transportType;
}
- (void)setTransport:(GRPCTransportId)transport {
_transport = transport;
}
- (void)setHostNameOverride:(NSString *)hostNameOverride {
_hostNameOverride = [hostNameOverride copy];
}

@ -0,0 +1,30 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* An object that processes its methods with a dispatch queue.
*/
@protocol GRPCDispatchable
/**
* The dispatch queue where the object's methods should be run on.
*/
@property(atomic, readonly) dispatch_queue_t dispatchQueue;
@end

@ -106,22 +106,20 @@
*/
#import "GRPCCall.h"
#import "GRPCDispatchable.h"
NS_ASSUME_NONNULL_BEGIN
@class GRPCInterceptorManager;
@class GRPCInterceptor;
@class GRPCRequestOptions;
@class GRPCCallOptions;
@protocol GRPCResponseHandler;
/**
* The GRPCInterceptorInterface defines the request events that can occur to an interceptr.
*/
@protocol GRPCInterceptorInterface<NSObject>
/**
* The queue on which all methods of this interceptor should be dispatched on. The queue must be a
* serial queue.
*/
@property(readonly) dispatch_queue_t requestDispatchQueue;
@protocol GRPCInterceptorInterface<NSObject, GRPCDispatchable>
/**
* To start the call. This method will only be called once for each instance.
@ -171,19 +169,20 @@ NS_ASSUME_NONNULL_BEGIN
* invoke shutDown method of its corresponding manager so that references to other interceptors can
* be released.
*/
@interface GRPCInterceptorManager : NSObject
@interface GRPCInterceptorManager : NSObject<GRPCInterceptorInterface, GRPCResponseHandler>
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype) new NS_UNAVAILABLE;
- (nullable instancetype)initWithNextInterceptor:(id<GRPCInterceptorInterface>)nextInterceptor
NS_DESIGNATED_INITIALIZER;
/** Set the previous interceptor in the chain. Can only be set once. */
- (void)setPreviousInterceptor:(id<GRPCResponseHandler>)previousInterceptor;
- (nullable instancetype)initWithFactories:(nullable NSArray<id<GRPCInterceptorFactory>> *)factories
previousInterceptor:(nullable id<GRPCResponseHandler>)previousInterceptor
transportId:(GRPCTransportId)transportId;
/** Indicate shutdown of the interceptor; release the reference to other interceptors */
/**
* Notify the manager that the interceptor has shut down and the manager should release references
* to other interceptors and stop forwarding requests/responses.
*/
- (void)shutDown;
// Methods to forward GRPCInterceptorInterface calls to the next interceptor
@ -235,7 +234,6 @@ NS_ASSUME_NONNULL_BEGIN
@interface GRPCInterceptor : NSObject<GRPCInterceptorInterface, GRPCResponseHandler>
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype) new NS_UNAVAILABLE;
/**
@ -243,9 +241,7 @@ NS_ASSUME_NONNULL_BEGIN
* that this interceptor's methods are dispatched onto.
*/
- (nullable instancetype)initWithInterceptorManager:(GRPCInterceptorManager *)interceptorManager
requestDispatchQueue:(dispatch_queue_t)requestDispatchQueue
responseDispatchQueue:(dispatch_queue_t)responseDispatchQueue
NS_DESIGNATED_INITIALIZER;
dispatchQueue:(dispatch_queue_t)dispatchQueue;
// Default implementation of GRPCInterceptorInterface

@ -19,117 +19,253 @@
#import <Foundation/Foundation.h>
#import "GRPCInterceptor.h"
#import "private/GRPCTransport+Private.h"
@interface GRPCInterceptorManager ()<GRPCInterceptorInterface, GRPCResponseHandler>
@end
@implementation GRPCInterceptorManager {
id<GRPCInterceptorInterface> _nextInterceptor;
id<GRPCResponseHandler> _previousInterceptor;
GRPCInterceptor *_thisInterceptor;
dispatch_queue_t _dispatchQueue;
NSArray<id<GRPCInterceptorFactory>> *_factories;
GRPCTransportId _transportId;
BOOL _shutDown;
}
- (instancetype)initWithNextInterceptor:(id<GRPCInterceptorInterface>)nextInterceptor {
- (instancetype)initWithFactories:(NSArray<id<GRPCInterceptorFactory>> *)factories
previousInterceptor:(id<GRPCResponseHandler>)previousInterceptor
transportId:(nonnull GRPCTransportId)transportId {
if ((self = [super init])) {
_nextInterceptor = nextInterceptor;
if (factories.count == 0) {
[NSException raise:NSInternalInconsistencyException
format:@"Interceptor manager must have factories"];
}
_thisInterceptor = [factories[0] createInterceptorWithManager:self];
if (_thisInterceptor == nil) {
return nil;
}
_previousInterceptor = previousInterceptor;
_factories = factories;
// Generate interceptor
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 || __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
if (@available(iOS 8.0, macOS 10.10, *)) {
_dispatchQueue = dispatch_queue_create(
NULL,
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0));
} else {
#else
{
#endif
_dispatchQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
}
dispatch_set_target_queue(_dispatchQueue, _thisInterceptor.dispatchQueue);
_transportId = transportId;
}
return self;
}
- (void)setPreviousInterceptor:(id<GRPCResponseHandler>)previousInterceptor {
_previousInterceptor = previousInterceptor;
- (void)shutDown {
dispatch_async(_dispatchQueue, ^{
self->_nextInterceptor = nil;
self->_previousInterceptor = nil;
self->_thisInterceptor = nil;
self->_shutDown = YES;
});
}
- (void)shutDown {
_nextInterceptor = nil;
_previousInterceptor = nil;
- (void)createNextInterceptor {
NSAssert(_nextInterceptor == nil, @"Starting the next interceptor more than once");
NSAssert(_factories.count > 0, @"Interceptor manager of transport cannot start next interceptor");
if (_nextInterceptor != nil) {
NSLog(@"Starting the next interceptor more than once");
return;
}
NSMutableArray<id<GRPCInterceptorFactory>> *interceptorFactories = [NSMutableArray
arrayWithArray:[_factories subarrayWithRange:NSMakeRange(1, _factories.count - 1)]];
while (_nextInterceptor == nil) {
if (interceptorFactories.count == 0) {
_nextInterceptor =
[[GRPCTransportManager alloc] initWithTransportId:_transportId previousInterceptor:self];
break;
} else {
_nextInterceptor = [[GRPCInterceptorManager alloc] initWithFactories:interceptorFactories
previousInterceptor:self
transportId:_transportId];
if (_nextInterceptor == nil) {
[interceptorFactories removeObjectAtIndex:0];
}
}
}
NSAssert(_nextInterceptor != nil, @"Failed to create interceptor or transport.");
if (_nextInterceptor == nil) {
NSLog(@"Failed to create interceptor or transport.");
}
}
- (void)startNextInterceptorWithRequest:(GRPCRequestOptions *)requestOptions
callOptions:(GRPCCallOptions *)callOptions {
if (_nextInterceptor != nil) {
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.requestDispatchQueue, ^{
[copiedNextInterceptor startWithRequestOptions:requestOptions callOptions:callOptions];
});
if (_nextInterceptor == nil && !_shutDown) {
[self createNextInterceptor];
}
if (_nextInterceptor == nil) {
return;
}
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.dispatchQueue, ^{
[copiedNextInterceptor startWithRequestOptions:requestOptions callOptions:callOptions];
});
}
- (void)writeNextInterceptorWithData:(id)data {
if (_nextInterceptor != nil) {
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.requestDispatchQueue, ^{
[copiedNextInterceptor writeData:data];
});
if (_nextInterceptor == nil && !_shutDown) {
[self createNextInterceptor];
}
if (_nextInterceptor == nil) {
return;
}
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.dispatchQueue, ^{
[copiedNextInterceptor writeData:data];
});
}
- (void)finishNextInterceptor {
if (_nextInterceptor != nil) {
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.requestDispatchQueue, ^{
[copiedNextInterceptor finish];
});
if (_nextInterceptor == nil && !_shutDown) {
[self createNextInterceptor];
}
if (_nextInterceptor == nil) {
return;
}
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.dispatchQueue, ^{
[copiedNextInterceptor finish];
});
}
- (void)cancelNextInterceptor {
if (_nextInterceptor != nil) {
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.requestDispatchQueue, ^{
[copiedNextInterceptor cancel];
});
if (_nextInterceptor == nil && !_shutDown) {
[self createNextInterceptor];
}
if (_nextInterceptor == nil) {
return;
}
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.dispatchQueue, ^{
[copiedNextInterceptor cancel];
});
}
/** Notify the next interceptor in the chain to receive more messages */
- (void)receiveNextInterceptorMessages:(NSUInteger)numberOfMessages {
if (_nextInterceptor != nil) {
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.requestDispatchQueue, ^{
[copiedNextInterceptor receiveNextMessages:numberOfMessages];
});
if (_nextInterceptor == nil && !_shutDown) {
[self createNextInterceptor];
}
if (_nextInterceptor == nil) {
return;
}
id<GRPCInterceptorInterface> copiedNextInterceptor = _nextInterceptor;
dispatch_async(copiedNextInterceptor.dispatchQueue, ^{
[copiedNextInterceptor receiveNextMessages:numberOfMessages];
});
}
// Methods to forward GRPCResponseHandler callbacks to the previous object
/** Forward initial metadata to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorWithInitialMetadata:(nullable NSDictionary *)initialMetadata {
if ([_previousInterceptor respondsToSelector:@selector(didReceiveInitialMetadata:)]) {
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didReceiveInitialMetadata:initialMetadata];
});
- (void)forwardPreviousInterceptorWithInitialMetadata:(NSDictionary *)initialMetadata {
if (_previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didReceiveInitialMetadata:initialMetadata];
});
}
/** Forward a received message to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorWithData:(id)data {
if ([_previousInterceptor respondsToSelector:@selector(didReceiveData:)]) {
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didReceiveData:data];
});
if (_previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didReceiveData:data];
});
}
/** Forward call close and trailing metadata to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorCloseWithTrailingMetadata:
(nullable NSDictionary *)trailingMetadata
error:(nullable NSError *)error {
if ([_previousInterceptor respondsToSelector:@selector(didCloseWithTrailingMetadata:error:)]) {
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didCloseWithTrailingMetadata:trailingMetadata error:error];
});
- (void)forwardPreviousInterceptorCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata
error:(NSError *)error {
if (_previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didCloseWithTrailingMetadata:trailingMetadata error:error];
});
}
/** Forward write completion to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorDidWriteData {
if ([_previousInterceptor respondsToSelector:@selector(didWriteData)]) {
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didWriteData];
});
if (_previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didWriteData];
});
}
- (dispatch_queue_t)dispatchQueue {
return _dispatchQueue;
}
- (void)startWithRequestOptions:(GRPCRequestOptions *)requestOptions
callOptions:(GRPCCallOptions *)callOptions {
[_thisInterceptor startWithRequestOptions:requestOptions callOptions:callOptions];
}
- (void)writeData:(id)data {
[_thisInterceptor writeData:data];
}
- (void)finish {
[_thisInterceptor finish];
}
- (void)cancel {
[_thisInterceptor cancel];
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages {
[_thisInterceptor receiveNextMessages:numberOfMessages];
}
- (void)didReceiveInitialMetadata:(nullable NSDictionary *)initialMetadata {
if ([_thisInterceptor respondsToSelector:@selector(didReceiveInitialMetadata:)]) {
[_thisInterceptor didReceiveInitialMetadata:initialMetadata];
}
}
- (void)didReceiveData:(id)data {
if ([_thisInterceptor respondsToSelector:@selector(didReceiveData:)]) {
[_thisInterceptor didReceiveData:data];
}
}
- (void)didCloseWithTrailingMetadata:(nullable NSDictionary *)trailingMetadata
error:(nullable NSError *)error {
if ([_thisInterceptor respondsToSelector:@selector(didCloseWithTrailingMetadata:error:)]) {
[_thisInterceptor didCloseWithTrailingMetadata:trailingMetadata error:error];
}
}
- (void)didWriteData {
if ([_thisInterceptor respondsToSelector:@selector(didWriteData)]) {
[_thisInterceptor didWriteData];
}
}
@ -137,28 +273,21 @@
@implementation GRPCInterceptor {
GRPCInterceptorManager *_manager;
dispatch_queue_t _requestDispatchQueue;
dispatch_queue_t _responseDispatchQueue;
dispatch_queue_t _dispatchQueue;
}
- (instancetype)initWithInterceptorManager:(GRPCInterceptorManager *)interceptorManager
requestDispatchQueue:(dispatch_queue_t)requestDispatchQueue
responseDispatchQueue:(dispatch_queue_t)responseDispatchQueue {
dispatchQueue:(dispatch_queue_t)dispatchQueue {
if ((self = [super init])) {
_manager = interceptorManager;
_requestDispatchQueue = requestDispatchQueue;
_responseDispatchQueue = responseDispatchQueue;
_dispatchQueue = dispatchQueue;
}
return self;
}
- (dispatch_queue_t)requestDispatchQueue {
return _requestDispatchQueue;
}
- (dispatch_queue_t)dispatchQueue {
return _responseDispatchQueue;
return _dispatchQueue;
}
- (void)startWithRequestOptions:(GRPCRequestOptions *)requestOptions

@ -0,0 +1,82 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// The interface for a transport implementation
#import "GRPCInterceptor.h"
NS_ASSUME_NONNULL_BEGIN
#pragma mark Transport ID
/**
* The default transport implementations available in gRPC. These implementations will be provided
* by gRPC by default unless explicitly excluded.
*/
extern const struct GRPCDefaultTransportImplList {
const GRPCTransportId core_secure;
const GRPCTransportId core_insecure;
} GRPCDefaultTransportImplList;
/** Returns whether two transport id's are identical. */
BOOL TransportIdIsEqual(GRPCTransportId lhs, GRPCTransportId rhs);
/** Returns the hash value of a transport id. */
NSUInteger TransportIdHash(GRPCTransportId);
#pragma mark Transport and factory
@protocol GRPCInterceptorInterface;
@protocol GRPCResponseHandler;
@class GRPCTransportManager;
@class GRPCRequestOptions;
@class GRPCCallOptions;
@class GRPCTransport;
/** The factory method to create a transport. */
@protocol GRPCTransportFactory<NSObject>
- (GRPCTransport *)createTransportWithManager:(GRPCTransportManager *)transportManager;
@end
/** The registry of transport implementations. */
@interface GRPCTransportRegistry : NSObject
+ (instancetype)sharedInstance;
/**
* Register a transport implementation with the registry. All transport implementations to be used
* in a process must register with the registry on process start-up in its +load: class method.
* Parameter \a transportId is the identifier of the implementation, and \a factory is the factory
* object to create the corresponding transport instance.
*/
- (void)registerTransportWithId:(GRPCTransportId)transportId
factory:(id<GRPCTransportFactory>)factory;
@end
/**
* Base class for transport implementations. All transport implementation should inherit from this
* class.
*/
@interface GRPCTransport : NSObject<GRPCInterceptorInterface>
@end
NS_ASSUME_NONNULL_END

@ -0,0 +1,142 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "GRPCTransport.h"
static const GRPCTransportId gGRPCCoreSecureId = "io.grpc.transport.core.secure";
static const GRPCTransportId gGRPCCoreInsecureId = "io.grpc.transport.core.insecure";
const struct GRPCDefaultTransportImplList GRPCDefaultTransportImplList = {
.core_secure = gGRPCCoreSecureId, .core_insecure = gGRPCCoreInsecureId};
static const GRPCTransportId gDefaultTransportId = gGRPCCoreSecureId;
static GRPCTransportRegistry *gTransportRegistry = nil;
static dispatch_once_t initTransportRegistry;
BOOL TransportIdIsEqual(GRPCTransportId lhs, GRPCTransportId rhs) {
// Directly comparing pointers works because we require users to use the id provided by each
// implementation, not coming up with their own string.
return lhs == rhs;
}
NSUInteger TransportIdHash(GRPCTransportId transportId) {
if (transportId == NULL) {
transportId = gDefaultTransportId;
}
return [NSString stringWithCString:transportId encoding:NSUTF8StringEncoding].hash;
}
@implementation GRPCTransportRegistry {
NSMutableDictionary<NSString *, id<GRPCTransportFactory>> *_registry;
id<GRPCTransportFactory> _defaultFactory;
}
+ (instancetype)sharedInstance {
dispatch_once(&initTransportRegistry, ^{
gTransportRegistry = [[GRPCTransportRegistry alloc] init];
NSAssert(gTransportRegistry != nil, @"Unable to initialize transport registry.");
if (gTransportRegistry == nil) {
NSLog(@"Unable to initialize transport registry.");
[NSException raise:NSGenericException format:@"Unable to initialize transport registry."];
}
});
return gTransportRegistry;
}
- (instancetype)init {
if ((self = [super init])) {
_registry = [NSMutableDictionary dictionary];
}
return self;
}
- (void)registerTransportWithId:(GRPCTransportId)transportId
factory:(id<GRPCTransportFactory>)factory {
NSString *nsTransportId = [NSString stringWithCString:transportId encoding:NSUTF8StringEncoding];
NSAssert(_registry[nsTransportId] == nil, @"The transport %@ has already been registered.",
nsTransportId);
if (_registry[nsTransportId] != nil) {
NSLog(@"The transport %@ has already been registered.", nsTransportId);
return;
}
_registry[nsTransportId] = factory;
// if the default transport is registered, mark it.
if (0 == strcmp(transportId, gDefaultTransportId)) {
_defaultFactory = factory;
}
}
- (id<GRPCTransportFactory>)getTransportFactoryWithId:(GRPCTransportId)transportId {
if (transportId == NULL) {
if (_defaultFactory == nil) {
[NSException raise:NSInvalidArgumentException
format:@"Unable to get default transport factory"];
return nil;
}
return _defaultFactory;
}
NSString *nsTransportId = [NSString stringWithCString:transportId encoding:NSUTF8StringEncoding];
id<GRPCTransportFactory> transportFactory = _registry[nsTransportId];
if (transportFactory == nil) {
// User named a transport id that was not registered with the registry.
[NSException raise:NSInvalidArgumentException
format:@"Unable to get transport factory with id %s", transportId];
return nil;
}
return transportFactory;
}
@end
@implementation GRPCTransport
- (dispatch_queue_t)dispatchQueue {
[NSException raise:NSGenericException
format:@"Implementations should override the dispatch queue"];
return nil;
}
- (void)startWithRequestOptions:(nonnull GRPCRequestOptions *)requestOptions
callOptions:(nonnull GRPCCallOptions *)callOptions {
[NSException raise:NSGenericException
format:@"Implementations should override the methods of GRPCTransport"];
}
- (void)writeData:(nonnull id)data {
[NSException raise:NSGenericException
format:@"Implementations should override the methods of GRPCTransport"];
}
- (void)cancel {
[NSException raise:NSGenericException
format:@"Implementations should override the methods of GRPCTransport"];
}
- (void)finish {
[NSException raise:NSGenericException
format:@"Implementations should override the methods of GRPCTransport"];
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages {
[NSException raise:NSGenericException
format:@"Implementations should override the methods of GRPCTransport"];
}
@end

@ -0,0 +1,187 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* gRPC error codes.
* Note that a few of these are never produced by the gRPC libraries, but are of
* general utility for server applications to produce.
*/
typedef NS_ENUM(NSUInteger, GRPCErrorCode) {
/** The operation was cancelled (typically by the caller). */
GRPCErrorCodeCancelled = 1,
/**
* Unknown error. Errors raised by APIs that do not return enough error
* information may be converted to this error.
*/
GRPCErrorCodeUnknown = 2,
/**
* The client specified an invalid argument. Note that this differs from
* FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
* problematic regardless of the state of the server (e.g., a malformed file
* name).
*/
GRPCErrorCodeInvalidArgument = 3,
/**
* Deadline expired before operation could complete. For operations that
* change the state of the server, this error may be returned even if the
* operation has completed successfully. For example, a successful response
* from the server could have been delayed long enough for the deadline to
* expire.
*/
GRPCErrorCodeDeadlineExceeded = 4,
/** Some requested entity (e.g., file or directory) was not found. */
GRPCErrorCodeNotFound = 5,
/** Some entity that we attempted to create (e.g., file or directory) already
exists. */
GRPCErrorCodeAlreadyExists = 6,
/**
* The caller does not have permission to execute the specified operation.
* PERMISSION_DENIED isn't used for rejections caused by exhausting some
* resource (RESOURCE_EXHAUSTED is used instead for those errors).
* PERMISSION_DENIED doesn't indicate a failure to identify the caller
* (UNAUTHENTICATED is used instead for those errors).
*/
GRPCErrorCodePermissionDenied = 7,
/**
* The request does not have valid authentication credentials for the
* operation (e.g. the caller's identity can't be verified).
*/
GRPCErrorCodeUnauthenticated = 16,
/** Some resource has been exhausted, perhaps a per-user quota. */
GRPCErrorCodeResourceExhausted = 8,
/**
* The RPC was rejected because the server is not in a state required for the
* procedure's execution. For example, a directory to be deleted may be
* non-empty, etc. The client should not retry until the server state has been
* explicitly fixed (e.g. by performing another RPC). The details depend on
* the service being called, and should be found in the NSError's userInfo.
*/
GRPCErrorCodeFailedPrecondition = 9,
/**
* The RPC was aborted, typically due to a concurrency issue like sequencer
* check failures, transaction aborts, etc. The client should retry at a
* higher-level (e.g., restarting a read- modify-write sequence).
*/
GRPCErrorCodeAborted = 10,
/**
* The RPC was attempted past the valid range. E.g., enumerating past the end
* of a list. Unlike INVALID_ARGUMENT, this error indicates a problem that may
* be fixed if the system state changes. For example, an RPC to get elements
* of a list will generate INVALID_ARGUMENT if asked to return the element at
* a negative index, but it will generate OUT_OF_RANGE if asked to return the
* element at an index past the current size of the list.
*/
GRPCErrorCodeOutOfRange = 11,
/** The procedure is not implemented or not supported/enabled in this server.
*/
GRPCErrorCodeUnimplemented = 12,
/**
* Internal error. Means some invariant expected by the server application or
* the gRPC library has been broken.
*/
GRPCErrorCodeInternal = 13,
/**
* The server is currently unavailable. This is most likely a transient
* condition and may be corrected by retrying with a backoff. Note that it is
* not always safe to retry non-idempotent operations.
*/
GRPCErrorCodeUnavailable = 14,
/** Unrecoverable data loss or corruption. */
GRPCErrorCodeDataLoss = 15,
};
/**
* Safety remark of a gRPC method as defined in RFC 2616 Section 9.1
*/
typedef NS_ENUM(NSUInteger, GRPCCallSafety) {
/**
* Signal that there is no guarantees on how the call affects the server
* state.
*/
GRPCCallSafetyDefault = 0,
/** Signal that the call is idempotent. gRPC is free to use PUT verb. */
GRPCCallSafetyIdempotentRequest = 1,
/**
* Signal that the call is cacheable and will not affect server state. gRPC is
* free to use GET verb.
*/
GRPCCallSafetyCacheableRequest = 2,
};
// Compression algorithm to be used by a gRPC call
typedef NS_ENUM(NSUInteger, GRPCCompressionAlgorithm) {
GRPCCompressNone = 0,
GRPCCompressDeflate,
GRPCCompressGzip,
GRPCStreamCompressGzip,
};
// GRPCCompressAlgorithm is deprecated; use GRPCCompressionAlgorithm
typedef GRPCCompressionAlgorithm GRPCCompressAlgorithm;
/** The transport to be used by a gRPC call */
typedef NS_ENUM(NSUInteger, GRPCTransportType) {
GRPCTransportTypeDefault = 0,
/** gRPC internal HTTP/2 stack with BoringSSL */
GRPCTransportTypeChttp2BoringSSL = 0,
/** Cronet stack */
GRPCTransportTypeCronet,
/** Insecure channel. FOR TEST ONLY! */
GRPCTransportTypeInsecure,
};
/** Domain of NSError objects produced by gRPC. */
extern NSString* _Nonnull const kGRPCErrorDomain;
/**
* Keys used in |NSError|'s |userInfo| dictionary to store the response headers
* and trailers sent by the server.
*/
extern NSString* _Nonnull const kGRPCHeadersKey;
extern NSString* _Nonnull const kGRPCTrailersKey;
/** The id of a transport implementation. */
typedef char* _Nonnull GRPCTransportId;
/**
* Implement this protocol to provide a token to gRPC when a call is initiated.
*/
@protocol GRPCAuthorizationProtocol
/**
* This method is called when gRPC is about to start the call. When OAuth token is acquired,
* \a handler is expected to be called with \a token being the new token to be used for this call.
*/
- (void)getTokenWithHandler:(void (^_Nonnull)(NSString* _Nullable token))handler;
@end

@ -20,7 +20,7 @@
#import "GRPCCall+InternalTests.h"
#import "../private/GRPCOpBatchLog.h"
#import "../private/GRPCCore/GRPCOpBatchLog.h"
@implementation GRPCCall (InternalTests)

@ -18,12 +18,6 @@
@interface GRPCCall (V2API)
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
callSafety:(GRPCCallSafety)safety
requestsWriter:(GRXWriter *)requestsWriter
callOptions:(GRPCCallOptions *)callOptions;
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
callSafety:(GRPCCallSafety)safety

@ -16,20 +16,22 @@
*
*/
#import <GRPCClient/GRPCInterceptor.h>
#import <GRPCClient/GRPCTransport.h>
NS_ASSUME_NONNULL_BEGIN
@interface GRPCCall2Internal : NSObject<GRPCInterceptorInterface>
@protocol GRPCResponseHandler;
@class GRPCCallOptions;
@protocol GRPCChannelFactory;
- (instancetype)init;
@interface GRPCCall2Internal : GRPCTransport
- (void)setResponseHandler:(id<GRPCResponseHandler>)responseHandler;
- (instancetype)initWithTransportManager:(GRPCTransportManager *)transportManager;
- (void)startWithRequestOptions:(GRPCRequestOptions *)requestOptions
callOptions:(nullable GRPCCallOptions *)callOptions;
callOptions:(GRPCCallOptions *)callOptions;
- (void)writeData:(NSData *)data;
- (void)writeData:(id)data;
- (void)finish;

@ -19,8 +19,10 @@
#import "GRPCCallInternal.h"
#import <GRPCClient/GRPCCall.h>
#import <GRPCClient/GRPCInterceptor.h>
#import <RxLibrary/GRXBufferedPipe.h>
#import "../GRPCTransport+Private.h"
#import "GRPCCall+V2API.h"
@implementation GRPCCall2Internal {
@ -28,8 +30,8 @@
GRPCRequestOptions *_requestOptions;
/** Options for the call. */
GRPCCallOptions *_callOptions;
/** The handler of responses. */
id<GRPCResponseHandler> _handler;
/** The interceptor manager to process responses. */
GRPCTransportManager *_transportManager;
/**
* Make use of legacy GRPCCall to make calls. Nullified when call is finished.
@ -51,40 +53,28 @@
NSUInteger _pendingReceiveNextMessages;
}
- (instancetype)init {
if ((self = [super init])) {
- (instancetype)initWithTransportManager:(GRPCTransportManager *)transportManager {
dispatch_queue_t dispatchQueue;
// Set queue QoS only when iOS version is 8.0 or above and Xcode version is 9.0 or above
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 || __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
if (@available(iOS 8.0, macOS 10.10, *)) {
_dispatchQueue = dispatch_queue_create(
NULL,
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0));
} else {
if (@available(iOS 8.0, macOS 10.10, *)) {
dispatchQueue = dispatch_queue_create(
NULL, dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0));
} else {
#else
{
{
#endif
_dispatchQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
}
dispatchQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
}
if ((self = [super init])) {
_pipe = [GRXBufferedPipe pipe];
_transportManager = transportManager;
_dispatchQueue = dispatchQueue;
}
return self;
}
- (void)setResponseHandler:(id<GRPCResponseHandler>)responseHandler {
@synchronized(self) {
NSAssert(!_started, @"Call already started.");
if (_started) {
return;
}
_handler = responseHandler;
_initialMetadataPublished = NO;
_started = NO;
_canceled = NO;
_finished = NO;
}
}
- (dispatch_queue_t)requestDispatchQueue {
- (dispatch_queue_t)dispatchQueue {
return _dispatchQueue;
}
@ -102,26 +92,15 @@
return;
}
GRPCCall *copiedCall = nil;
@synchronized(self) {
NSAssert(_handler != nil, @"Response handler required.");
if (_handler == nil) {
NSLog(@"Invalid response handler.");
return;
}
_requestOptions = requestOptions;
if (callOptions == nil) {
_callOptions = [[GRPCCallOptions alloc] init];
} else {
_callOptions = [callOptions copy];
}
}
[self start];
}
- (void)start {
GRPCCall *copiedCall = nil;
@synchronized(self) {
NSAssert(!_started, @"Call already started.");
NSAssert(!_canceled, @"Call already canceled.");
if (_started) {
@ -140,7 +119,7 @@
callOptions:_callOptions
writeDone:^{
@synchronized(self) {
if (self->_handler) {
if (self->_transportManager) {
[self issueDidWriteData];
}
}
@ -158,7 +137,7 @@
void (^valueHandler)(id value) = ^(id value) {
@synchronized(self) {
if (self->_handler) {
if (self->_transportManager) {
if (!self->_initialMetadataPublished) {
self->_initialMetadataPublished = YES;
[self issueInitialMetadata:self->_call.responseHeaders];
@ -171,7 +150,7 @@
};
void (^completionHandler)(NSError *errorOrNil) = ^(NSError *errorOrNil) {
@synchronized(self) {
if (self->_handler) {
if (self->_transportManager) {
if (!self->_initialMetadataPublished) {
self->_initialMetadataPublished = YES;
[self issueInitialMetadata:self->_call.responseHeaders];
@ -207,20 +186,19 @@
_call = nil;
_pipe = nil;
if ([_handler respondsToSelector:@selector(didCloseWithTrailingMetadata:error:)]) {
id<GRPCResponseHandler> copiedHandler = _handler;
_handler = nil;
dispatch_async(copiedHandler.dispatchQueue, ^{
[copiedHandler didCloseWithTrailingMetadata:nil
error:[NSError errorWithDomain:kGRPCErrorDomain
code:GRPCErrorCodeCancelled
userInfo:@{
NSLocalizedDescriptionKey :
@"Canceled by app"
}]];
});
} else {
_handler = nil;
if (_transportManager != nil) {
[_transportManager
forwardPreviousInterceptorCloseWithTrailingMetadata:nil
error:
[NSError
errorWithDomain:kGRPCErrorDomain
code:
GRPCErrorCodeCancelled
userInfo:@{
NSLocalizedDescriptionKey :
@"Canceled by app"
}]];
[_transportManager shutDown];
}
}
[copiedCall cancel];
@ -271,59 +249,25 @@
}
- (void)issueInitialMetadata:(NSDictionary *)initialMetadata {
@synchronized(self) {
if (initialMetadata != nil &&
[_handler respondsToSelector:@selector(didReceiveInitialMetadata:)]) {
id<GRPCResponseHandler> copiedHandler = _handler;
dispatch_async(_handler.dispatchQueue, ^{
[copiedHandler didReceiveInitialMetadata:initialMetadata];
});
}
if (initialMetadata != nil) {
[_transportManager forwardPreviousInterceptorWithInitialMetadata:initialMetadata];
}
}
- (void)issueMessage:(id)message {
@synchronized(self) {
if (message != nil) {
if ([_handler respondsToSelector:@selector(didReceiveData:)]) {
id<GRPCResponseHandler> copiedHandler = _handler;
dispatch_async(_handler.dispatchQueue, ^{
[copiedHandler didReceiveData:message];
});
} else if ([_handler respondsToSelector:@selector(didReceiveRawMessage:)]) {
id<GRPCResponseHandler> copiedHandler = _handler;
dispatch_async(_handler.dispatchQueue, ^{
[copiedHandler didReceiveRawMessage:message];
});
}
}
if (message != nil) {
[_transportManager forwardPreviousInterceptorWithData:message];
}
}
- (void)issueClosedWithTrailingMetadata:(NSDictionary *)trailingMetadata error:(NSError *)error {
@synchronized(self) {
if ([_handler respondsToSelector:@selector(didCloseWithTrailingMetadata:error:)]) {
id<GRPCResponseHandler> copiedHandler = _handler;
// Clean up _handler so that no more responses are reported to the handler.
_handler = nil;
dispatch_async(copiedHandler.dispatchQueue, ^{
[copiedHandler didCloseWithTrailingMetadata:trailingMetadata error:error];
});
} else {
_handler = nil;
}
}
[_transportManager forwardPreviousInterceptorCloseWithTrailingMetadata:trailingMetadata
error:error];
[_transportManager shutDown];
}
- (void)issueDidWriteData {
@synchronized(self) {
if (_callOptions.flowControlEnabled && [_handler respondsToSelector:@selector(didWriteData)]) {
id<GRPCResponseHandler> copiedHandler = _handler;
dispatch_async(copiedHandler.dispatchQueue, ^{
[copiedHandler didWriteData];
});
}
}
[_transportManager forwardPreviousInterceptorDidWriteData];
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages {

@ -20,18 +20,19 @@
#include <grpc/support/log.h>
#import "../internal/GRPCCallOptions+Internal.h"
#import "../../internal/GRPCCallOptions+Internal.h"
#import "../GRPCTransport+Private.h"
#import "ChannelArgsUtil.h"
#import "GRPCChannelFactory.h"
#import "GRPCChannelPool.h"
#import "GRPCCompletionQueue.h"
#import "GRPCCronetChannelFactory.h"
#import "GRPCCoreFactory.h"
#import "GRPCInsecureChannelFactory.h"
#import "GRPCSecureChannelFactory.h"
#import "version.h"
#import <GRPCClient/GRPCCall+Cronet.h>
#import <GRPCClient/GRPCCallOptions.h>
#import <GRPCClient/version.h>
@implementation GRPCChannelConfiguration
@ -50,32 +51,48 @@
}
- (id<GRPCChannelFactory>)channelFactory {
GRPCTransportType type = _callOptions.transportType;
switch (type) {
case GRPCTransportTypeChttp2BoringSSL:
// TODO (mxyan): Remove when the API is deprecated
#ifdef GRPC_COMPILE_WITH_CRONET
if (![GRPCCall isUsingCronet]) {
#else
{
#endif
NSError *error;
id<GRPCChannelFactory> factory = [GRPCSecureChannelFactory
factoryWithPEMRootCertificates:_callOptions.PEMRootCertificates
privateKey:_callOptions.PEMPrivateKey
certChain:_callOptions.PEMCertificateChain
error:&error];
NSAssert(factory != nil, @"Failed to create secure channel factory");
if (factory == nil) {
NSLog(@"Error creating secure channel factory: %@", error);
if (_callOptions.transport != NULL) {
id<GRPCTransportFactory> transportFactory =
[[GRPCTransportRegistry sharedInstance] getTransportFactoryWithId:_callOptions.transport];
if (!
[transportFactory respondsToSelector:@selector(createCoreChannelFactoryWithCallOptions:)]) {
// impossible because we are using GRPCCore now
[NSException raise:NSInternalInconsistencyException
format:@"Transport factory type is wrong"];
}
id<GRPCCoreTransportFactory> coreTransportFactory =
(id<GRPCCoreTransportFactory>)transportFactory;
return [coreTransportFactory createCoreChannelFactoryWithCallOptions:_callOptions];
} else {
// To maintain backwards compatibility with tranportType
GRPCTransportType type = _callOptions.transportType;
switch (type) {
case GRPCTransportTypeChttp2BoringSSL:
// TODO (mxyan): Remove when the API is deprecated
{
NSError *error;
id<GRPCChannelFactory> factory = [GRPCSecureChannelFactory
factoryWithPEMRootCertificates:_callOptions.PEMRootCertificates
privateKey:_callOptions.PEMPrivateKey
certChain:_callOptions.PEMCertificateChain
error:&error];
NSAssert(factory != nil, @"Failed to create secure channel factory");
if (factory == nil) {
NSLog(@"Error creating secure channel factory: %@", error);
}
return factory;
}
return factory;
case GRPCTransportTypeCronet: {
id<GRPCCoreTransportFactory> transportFactory = (id<GRPCCoreTransportFactory>)[
[GRPCTransportRegistry sharedInstance] getTransportFactoryWithId:gGRPCCoreCronetId];
return [transportFactory createCoreChannelFactoryWithCallOptions:_callOptions];
}
// fallthrough
case GRPCTransportTypeCronet:
return [GRPCCronetChannelFactory sharedInstance];
case GRPCTransportTypeInsecure:
return [GRPCInsecureChannelFactory sharedInstance];
case GRPCTransportTypeInsecure:
return [GRPCInsecureChannelFactory sharedInstance];
default:
NSLog(@"Unrecognized transport type");
return nil;
}
}
}
@ -198,6 +215,7 @@
} else {
channelArgs = channelConfiguration.channelArgs;
}
id<GRPCChannelFactory> factory = channelConfiguration.channelFactory;
_unmanagedChannel = [factory createChannelWithHost:host channelArgs:channelArgs];
NSAssert(_unmanagedChannel != NULL, @"Failed to create channel");

@ -18,8 +18,6 @@
#import <GRPCClient/GRPCCallOptions.h>
#import "GRPCChannelFactory.h"
NS_ASSUME_NONNULL_BEGIN
@protocol GRPCChannel;

@ -18,19 +18,16 @@
#import <Foundation/Foundation.h>
#import "../internal/GRPCCallOptions+Internal.h"
#import "../../internal/GRPCCallOptions+Internal.h"
#import "GRPCChannel.h"
#import "GRPCChannelFactory.h"
#import "GRPCChannelPool+Test.h"
#import "GRPCChannelPool.h"
#import "GRPCCompletionQueue.h"
#import "GRPCCronetChannelFactory.h"
#import "GRPCInsecureChannelFactory.h"
#import "GRPCSecureChannelFactory.h"
#import "GRPCWrappedCall.h"
#import "version.h"
#import <GRPCClient/GRPCCall+Cronet.h>
#include <grpc/support/log.h>
extern const char *kCFStreamVarName;

@ -0,0 +1,32 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "../GRPCCoreFactory.h"
/**
* The factory for gRPC Core + Cronet transport implementation. The
* implementation is not part of the default transports of gRPC and is for
* testing purpose only on Github.
*
* To use this transport, a user must include the GRPCCoreCronet module as a
* dependency of the project and use gGRPCCoreCronetId in call options to
* specify that this is the transport to be used for a call.
*/
@interface GRPCCoreCronetFactory : NSObject<GRPCCoreTransportFactory>
@end

@ -0,0 +1,54 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "GRPCCoreCronetFactory.h"
#import <GRPCClient/GRPCCall+Cronet.h>
#import <GRPCClient/GRPCTransport.h>
#import "../GRPCCallInternal.h"
#import "../GRPCCoreFactory.h"
#import "GRPCCronetChannelFactory.h"
static GRPCCoreCronetFactory *gGRPCCoreCronetFactory = nil;
static dispatch_once_t gInitGRPCCoreCronetFactory;
@implementation GRPCCoreCronetFactory
+ (instancetype)sharedInstance {
dispatch_once(&gInitGRPCCoreCronetFactory, ^{
gGRPCCoreCronetFactory = [[GRPCCoreCronetFactory alloc] init];
});
return gGRPCCoreCronetFactory;
}
+ (void)load {
[[GRPCTransportRegistry sharedInstance]
registerTransportWithId:gGRPCCoreCronetId
factory:[GRPCCoreCronetFactory sharedInstance]];
}
- (GRPCTransport *)createTransportWithManager:(GRPCTransportManager *)transportManager {
return [[GRPCCall2Internal alloc] initWithTransportManager:transportManager];
}
- (id<GRPCChannelFactory>)createCoreChannelFactoryWithCallOptions:(GRPCCallOptions *)callOptions {
return [GRPCCronetChannelFactory sharedInstance];
}
@end

@ -15,7 +15,7 @@
* limitations under the License.
*
*/
#import "GRPCChannelFactory.h"
#import "../GRPCChannelFactory.h"
@class GRPCChannel;
typedef struct stream_engine stream_engine;

@ -18,10 +18,8 @@
#import "GRPCCronetChannelFactory.h"
#import "ChannelArgsUtil.h"
#import "GRPCChannel.h"
#ifdef GRPC_COMPILE_WITH_CRONET
#import "../ChannelArgsUtil.h"
#import "../GRPCChannel.h"
#import <Cronet/Cronet.h>
#include <grpc/grpc_cronet.h>
@ -59,21 +57,3 @@
}
@end
#else
@implementation GRPCCronetChannelFactory
+ (instancetype)sharedInstance {
NSAssert(NO, @"Must enable macro GRPC_COMPILE_WITH_CRONET to build Cronet channel.");
return nil;
}
- (grpc_channel *)createChannelWithHost:(NSString *)host channelArgs:(NSDictionary *)args {
NSAssert(NO, @"Must enable macro GRPC_COMPILE_WITH_CRONET to build Cronet channel.");
return NULL;
}
@end
#endif

@ -0,0 +1,45 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import <GRPCClient/GRPCTransport.h>
NS_ASSUME_NONNULL_BEGIN
@protocol GRPCChannelFactory;
@protocol GRPCCallOptions;
/** The interface for transport implementations that are based on Core. */
@protocol GRPCCoreTransportFactory<GRPCTransportFactory>
/** Get the channel factory for GRPCChannel from call options. */
- (nullable id<GRPCChannelFactory>)createCoreChannelFactoryWithCallOptions:
(GRPCCallOptions *)callOptions;
@end
/** The factory for gRPC Core + CFStream + TLS secure channel transport implementation. */
@interface GRPCCoreSecureFactory : NSObject<GRPCCoreTransportFactory>
@end
/** The factory for gRPC Core + CFStream + insecure channel transport implementation. */
@interface GRPCCoreInsecureFactory : NSObject<GRPCCoreTransportFactory>
@end
NS_ASSUME_NONNULL_END

@ -0,0 +1,90 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "GRPCCoreFactory.h"
#import <GRPCClient/GRPCTransport.h>
#import "GRPCCallInternal.h"
#import "GRPCInsecureChannelFactory.h"
#import "GRPCSecureChannelFactory.h"
static GRPCCoreSecureFactory *gGRPCCoreSecureFactory = nil;
static GRPCCoreInsecureFactory *gGRPCCoreInsecureFactory = nil;
static dispatch_once_t gInitGRPCCoreSecureFactory;
static dispatch_once_t gInitGRPCCoreInsecureFactory;
@implementation GRPCCoreSecureFactory
+ (instancetype)sharedInstance {
dispatch_once(&gInitGRPCCoreSecureFactory, ^{
gGRPCCoreSecureFactory = [[GRPCCoreSecureFactory alloc] init];
});
return gGRPCCoreSecureFactory;
}
+ (void)load {
[[GRPCTransportRegistry sharedInstance]
registerTransportWithId:GRPCDefaultTransportImplList.core_secure
factory:[self sharedInstance]];
}
- (GRPCTransport *)createTransportWithManager:(GRPCTransportManager *)transportManager {
return [[GRPCCall2Internal alloc] initWithTransportManager:transportManager];
}
- (id<GRPCChannelFactory>)createCoreChannelFactoryWithCallOptions:(GRPCCallOptions *)callOptions {
NSError *error;
id<GRPCChannelFactory> factory =
[GRPCSecureChannelFactory factoryWithPEMRootCertificates:callOptions.PEMRootCertificates
privateKey:callOptions.PEMPrivateKey
certChain:callOptions.PEMCertificateChain
error:&error];
if (error != nil) {
NSLog(@"Unable to create secure channel factory");
return nil;
}
return factory;
}
@end
@implementation GRPCCoreInsecureFactory
+ (instancetype)sharedInstance {
dispatch_once(&gInitGRPCCoreInsecureFactory, ^{
gGRPCCoreInsecureFactory = [[GRPCCoreInsecureFactory alloc] init];
});
return gGRPCCoreInsecureFactory;
}
+ (void)load {
[[GRPCTransportRegistry sharedInstance]
registerTransportWithId:GRPCDefaultTransportImplList.core_insecure
factory:[self sharedInstance]];
}
- (GRPCTransport *)createTransportWithManager:(GRPCTransportManager *)transportManager {
return [[GRPCCall2Internal alloc] initWithTransportManager:transportManager];
}
- (id<GRPCChannelFactory>)createCoreChannelFactoryWithCallOptions:(GRPCCallOptions *)callOptions {
return [GRPCInsecureChannelFactory sharedInstance];
}
@end

@ -21,17 +21,16 @@
#import <GRPCClient/GRPCCall+Cronet.h>
#import <GRPCClient/GRPCCall.h>
#import <GRPCClient/GRPCCallOptions.h>
#import <GRPCClient/GRPCTransport.h>
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#import "../internal/GRPCCallOptions+Internal.h"
#import "../../internal/GRPCCallOptions+Internal.h"
#import "GRPCChannelFactory.h"
#import "GRPCCompletionQueue.h"
#import "GRPCCronetChannelFactory.h"
#import "GRPCSecureChannelFactory.h"
#import "NSDictionary+GRPC.h"
#import "version.h"
NS_ASSUME_NONNULL_BEGIN
@ -113,20 +112,12 @@ static NSMutableDictionary *gHostCache;
options.PEMPrivateKey = _PEMPrivateKey;
options.PEMCertificateChain = _PEMCertificateChain;
options.hostNameOverride = _hostNameOverride;
#ifdef GRPC_COMPILE_WITH_CRONET
// By old API logic, insecure channel precedes Cronet channel; Cronet channel preceeds default
// channel.
if ([GRPCCall isUsingCronet]) {
if (_transportType == GRPCTransportTypeInsecure) {
options.transportType = GRPCTransportTypeInsecure;
} else {
NSAssert(_transportType == GRPCTransportTypeDefault, @"Invalid transport type");
options.transportType = GRPCTransportTypeCronet;
}
} else
#endif
{
options.transportType = _transportType;
if (_transportType == GRPCTransportTypeInsecure) {
options.transport = GRPCDefaultTransportImplList.core_insecure;
} else if ([GRPCCall isUsingCronet]) {
options.transport = gGRPCCoreCronetId;
} else {
options.transport = GRPCDefaultTransportImplList.core_secure;
}
options.logContext = _logContext;
@ -135,16 +126,14 @@ static NSMutableDictionary *gHostCache;
+ (GRPCCallOptions *)callOptionsForHost:(NSString *)host {
// TODO (mxyan): Remove when old API is deprecated
NSURL *hostURL = [NSURL URLWithString:[@"https://" stringByAppendingString:host]];
if (hostURL.host && hostURL.port == nil) {
host = [hostURL.host stringByAppendingString:@":443"];
}
GRPCCallOptions *callOptions = nil;
@synchronized(gHostCache) {
callOptions = [gHostCache[host] callOptions];
GRPCHost *hostConfig = [GRPCHost hostWithAddress:host];
callOptions = [hostConfig callOptions];
}
NSAssert(callOptions != nil, @"Unable to create call options object");
if (callOptions == nil) {
NSLog(@"Unable to create call options object");
callOptions = [[GRPCCallOptions alloc] init];
}
return callOptions;

@ -18,7 +18,7 @@
#import <Foundation/Foundation.h>
#import "../GRPCCall.h"
#import <GRPCClient/GRPCCallLegacy.h>
@interface GRPCRequestHeaders : NSMutableDictionary

@ -18,10 +18,9 @@
#import "NSError+GRPC.h"
#import <GRPCClient/GRPCTypes.h>
#include <grpc/grpc.h>
NSString *const kGRPCErrorDomain = @"io.grpc";
@implementation NSError (GRPC)
+ (instancetype)grpc_errorFromStatusCode:(grpc_status_code)statusCode
details:(const char *)details

@ -0,0 +1,65 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import <GRPCClient/GRPCInterceptor.h>
#import <GRPCClient/GRPCTransport.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Private interfaces of the transport registry.
*/
@interface GRPCTransportRegistry (Private)
/**
* Get a transport implementation's factory by its transport id. If the transport id was not
* registered with the registry, the default transport factory (core + secure) is returned. If the
* default transport does not exist, an exception is thrown.
*/
- (id<GRPCTransportFactory>)getTransportFactoryWithId:(GRPCTransportId)transportId;
@end
@interface GRPCTransportManager : NSObject<GRPCInterceptorInterface>
- (instancetype)initWithTransportId:(GRPCTransportId)transportId
previousInterceptor:(id<GRPCResponseHandler>)previousInterceptor;
/**
* Notify the manager that the transport has shut down and the manager should release references to
* its response handler and stop forwarding requests/responses.
*/
- (void)shutDown;
/** Forward initial metadata to the previous interceptor in the interceptor chain */
- (void)forwardPreviousInterceptorWithInitialMetadata:(nullable NSDictionary *)initialMetadata;
/** Forward a received message to the previous interceptor in the interceptor chain */
- (void)forwardPreviousInterceptorWithData:(nullable id)data;
/** Forward call close and trailing metadata to the previous interceptor in the interceptor chain */
- (void)forwardPreviousInterceptorCloseWithTrailingMetadata:
(nullable NSDictionary *)trailingMetadata
error:(nullable NSError *)error;
/** Forward write completion to the previous interceptor in the interceptor chain */
- (void)forwardPreviousInterceptorDidWriteData;
@end
NS_ASSUME_NONNULL_END

@ -0,0 +1,131 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "GRPCTransport+Private.h"
#import <GRPCClient/GRPCTransport.h>
@implementation GRPCTransportManager {
GRPCTransportId _transportId;
GRPCTransport *_transport;
id<GRPCResponseHandler> _previousInterceptor;
dispatch_queue_t _dispatchQueue;
}
- (instancetype)initWithTransportId:(GRPCTransportId)transportId
previousInterceptor:(id<GRPCResponseHandler>)previousInterceptor {
if ((self = [super init])) {
id<GRPCTransportFactory> factory =
[[GRPCTransportRegistry sharedInstance] getTransportFactoryWithId:transportId];
_transport = [factory createTransportWithManager:self];
NSAssert(_transport != nil, @"Failed to create transport with id: %s", transportId);
if (_transport == nil) {
NSLog(@"Failed to create transport with id: %s", transportId);
return nil;
}
_previousInterceptor = previousInterceptor;
_dispatchQueue = _transport.dispatchQueue;
_transportId = transportId;
}
return self;
}
- (void)shutDown {
dispatch_async(_dispatchQueue, ^{
self->_transport = nil;
self->_previousInterceptor = nil;
});
}
- (dispatch_queue_t)dispatchQueue {
return _dispatchQueue;
}
- (void)startWithRequestOptions:(GRPCRequestOptions *)requestOptions
callOptions:(GRPCCallOptions *)callOptions {
if (_transportId != callOptions.transport) {
[NSException raise:NSInvalidArgumentException
format:@"Interceptors cannot change the call option 'transport'"];
return;
}
[_transport startWithRequestOptions:requestOptions callOptions:callOptions];
}
- (void)writeData:(id)data {
[_transport writeData:data];
}
- (void)finish {
[_transport finish];
}
- (void)cancel {
[_transport cancel];
}
- (void)receiveNextMessages:(NSUInteger)numberOfMessages {
[_transport receiveNextMessages:numberOfMessages];
}
/** Forward initial metadata to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorWithInitialMetadata:(NSDictionary *)initialMetadata {
if (initialMetadata == nil || _previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didReceiveInitialMetadata:initialMetadata];
});
}
/** Forward a received message to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorWithData:(id)data {
if (data == nil || _previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didReceiveData:data];
});
}
/** Forward call close and trailing metadata to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata
error:(NSError *)error {
if (_previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didCloseWithTrailingMetadata:trailingMetadata error:error];
});
}
/** Forward write completion to the previous interceptor in the chain */
- (void)forwardPreviousInterceptorDidWriteData {
if (_previousInterceptor == nil) {
return;
}
id<GRPCResponseHandler> copiedPreviousInterceptor = _previousInterceptor;
dispatch_async(copiedPreviousInterceptor.dispatchQueue, ^{
[copiedPreviousInterceptor didWriteData];
});
}
@end

@ -17,12 +17,16 @@
*/
#import <Foundation/Foundation.h>
#import <GRPCClient/GRPCCall.h>
// import legacy header for compatibility with users using the ProtoRPC interface
#import "ProtoRPCLegacy.h"
#import "ProtoMethod.h"
NS_ASSUME_NONNULL_BEGIN
@class GRPCRequestOptions;
@class GRPCCallOptions;
@class GPBMessage;
/** An object can implement this protocol to receive responses from server from a call. */
@ -160,35 +164,3 @@ NS_ASSUME_NONNULL_BEGIN
@end
NS_ASSUME_NONNULL_END
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability-completeness"
__attribute__((deprecated("Please use GRPCProtoCall."))) @interface ProtoRPC
: GRPCCall
/**
* host parameter should not contain the scheme (http:// or https://), only the name or IP
* addr and the port number, for example @"localhost:5050".
*/
-
(instancetype)initWithHost : (NSString *)host method
: (GRPCProtoMethod *)method requestsWriter : (GRXWriter *)requestsWriter responseClass
: (Class)responseClass responsesWriteable
: (id<GRXWriteable>)responsesWriteable NS_DESIGNATED_INITIALIZER;
- (void)start;
@end
/**
* This subclass is empty now. Eventually we'll remove ProtoRPC class
* to avoid potential naming conflict
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@interface GRPCProtoCall : ProtoRPC
#pragma clang diagnostic pop
@end
#pragma clang diagnostic pop

@ -27,24 +27,6 @@
#import <RxLibrary/GRXWriteable.h>
#import <RxLibrary/GRXWriter+Transformations.h>
/**
* Generate an NSError object that represents a failure in parsing a proto class.
*/
static NSError *ErrorForBadProto(id proto, Class expectedClass, NSError *parsingError) {
NSDictionary *info = @{
NSLocalizedDescriptionKey : @"Unable to parse response from the server",
NSLocalizedRecoverySuggestionErrorKey :
@"If this RPC is idempotent, retry "
@"with exponential backoff. Otherwise, query the server status before "
@"retrying.",
NSUnderlyingErrorKey : parsingError,
@"Expected class" : expectedClass,
@"Received value" : proto,
};
// TODO(jcanizales): Use kGRPCErrorDomain and GRPCErrorCodeInternal when they're public.
return [NSError errorWithDomain:@"io.grpc" code:13 userInfo:info];
}
@implementation GRPCUnaryProtoCall {
GRPCStreamingProtoCall *_call;
GPBMessage *_message;
@ -291,76 +273,3 @@ static NSError *ErrorForBadProto(id proto, Class expectedClass, NSError *parsing
}
@end
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
@implementation ProtoRPC {
#pragma clang diagnostic pop
id<GRXWriteable> _responseWriteable;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
requestsWriter:(GRXWriter *)requestsWriter {
[NSException raise:NSInvalidArgumentException
format:@"Please use ProtoRPC's designated initializer instead."];
return nil;
}
#pragma clang diagnostic pop
// Designated initializer
- (instancetype)initWithHost:(NSString *)host
method:(GRPCProtoMethod *)method
requestsWriter:(GRXWriter *)requestsWriter
responseClass:(Class)responseClass
responsesWriteable:(id<GRXWriteable>)responsesWriteable {
// Because we can't tell the type system to constrain the class, we need to check at runtime:
if (![responseClass respondsToSelector:@selector(parseFromData:error:)]) {
[NSException raise:NSInvalidArgumentException
format:@"A protobuf class to parse the responses must be provided."];
}
// A writer that serializes the proto messages to send.
GRXWriter *bytesWriter = [requestsWriter map:^id(GPBMessage *proto) {
if (![proto isKindOfClass:[GPBMessage class]]) {
[NSException raise:NSInvalidArgumentException
format:@"Request must be a proto message: %@", proto];
}
return [proto data];
}];
if ((self = [super initWithHost:host path:method.HTTPPath requestsWriter:bytesWriter])) {
__weak ProtoRPC *weakSelf = self;
// A writeable that parses the proto messages received.
_responseWriteable = [[GRXWriteable alloc] initWithValueHandler:^(NSData *value) {
// TODO(jcanizales): This is done in the main thread, and needs to happen in another thread.
NSError *error = nil;
id parsed = [responseClass parseFromData:value error:&error];
if (parsed) {
[responsesWriteable writeValue:parsed];
} else {
[weakSelf finishWithError:ErrorForBadProto(value, responseClass, error)];
}
}
completionHandler:^(NSError *errorOrNil) {
[responsesWriteable writesFinishedWithError:errorOrNil];
}];
}
return self;
}
- (void)start {
[self startWithWriteable:_responseWriteable];
}
- (void)startWithWriteable:(id<GRXWriteable>)writeable {
[super startWithWriteable:writeable];
// Break retain cycles.
_responseWriteable = nil;
}
@end
@implementation GRPCProtoCall
@end

@ -0,0 +1,67 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import <GRPCClient/GRPCCallLegacy.h>
// Import category headers for Swift build
#import <GRPCClient/GRPCCall+ChannelArg.h>
#import <GRPCClient/GRPCCall+ChannelCredentials.h>
#import <GRPCClient/GRPCCall+Cronet.h>
#import <GRPCClient/GRPCCall+OAuth2.h>
#import <GRPCClient/GRPCCall+Tests.h>
#import <RxLibrary/GRXWriteable.h>
@class GRPCProtoMethod;
@class GRXWriter;
@protocol GRXWriteable;
__attribute__((deprecated("Please use GRPCProtoCall."))) @interface ProtoRPC
: GRPCCall
/**
* host parameter should not contain the scheme (http:// or https://), only the name or IP
* addr and the port number, for example @"localhost:5050".
*/
-
(instancetype)initWithHost : (NSString *)host method
: (GRPCProtoMethod *)method requestsWriter : (GRXWriter *)requestsWriter responseClass
: (Class)responseClass responsesWriteable
: (id<GRXWriteable>)responsesWriteable NS_DESIGNATED_INITIALIZER;
- (void)start;
@end
/**
* This subclass is empty now. Eventually we'll remove ProtoRPC class
* to avoid potential naming conflict
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@interface GRPCProtoCall
: ProtoRPC
#pragma clang diagnostic pop
@end
/**
* Generate an NSError object that represents a failure in parsing a proto class. For gRPC
* internal use only.
*/
NSError *
ErrorForBadProto(id proto, Class expectedClass, NSError *parsingError);

@ -0,0 +1,121 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "ProtoRPCLegacy.h"
#import "ProtoMethod.h"
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
#import <Protobuf/GPBProtocolBuffers.h>
#else
#import <GPBProtocolBuffers.h>
#endif
#import <GRPCClient/GRPCCall.h>
#import <RxLibrary/GRXWriteable.h>
#import <RxLibrary/GRXWriter+Transformations.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
@implementation ProtoRPC {
#pragma clang diagnostic pop
id<GRXWriteable> _responseWriteable;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
- (instancetype)initWithHost:(NSString *)host
path:(NSString *)path
requestsWriter:(GRXWriter *)requestsWriter {
[NSException raise:NSInvalidArgumentException
format:@"Please use ProtoRPC's designated initializer instead."];
return nil;
}
#pragma clang diagnostic pop
// Designated initializer
- (instancetype)initWithHost:(NSString *)host
method:(GRPCProtoMethod *)method
requestsWriter:(GRXWriter *)requestsWriter
responseClass:(Class)responseClass
responsesWriteable:(id<GRXWriteable>)responsesWriteable {
// Because we can't tell the type system to constrain the class, we need to check at runtime:
if (![responseClass respondsToSelector:@selector(parseFromData:error:)]) {
[NSException raise:NSInvalidArgumentException
format:@"A protobuf class to parse the responses must be provided."];
}
// A writer that serializes the proto messages to send.
GRXWriter *bytesWriter = [requestsWriter map:^id(GPBMessage *proto) {
if (![proto isKindOfClass:[GPBMessage class]]) {
[NSException raise:NSInvalidArgumentException
format:@"Request must be a proto message: %@", proto];
}
return [proto data];
}];
if ((self = [super initWithHost:host path:method.HTTPPath requestsWriter:bytesWriter])) {
__weak ProtoRPC *weakSelf = self;
// A writeable that parses the proto messages received.
_responseWriteable = [[GRXWriteable alloc] initWithValueHandler:^(NSData *value) {
// TODO(jcanizales): This is done in the main thread, and needs to happen in another thread.
NSError *error = nil;
id parsed = [responseClass parseFromData:value error:&error];
if (parsed) {
[responsesWriteable writeValue:parsed];
} else {
[weakSelf finishWithError:ErrorForBadProto(value, responseClass, error)];
}
}
completionHandler:^(NSError *errorOrNil) {
[responsesWriteable writesFinishedWithError:errorOrNil];
}];
}
return self;
}
- (void)start {
[self startWithWriteable:_responseWriteable];
}
- (void)startWithWriteable:(id<GRXWriteable>)writeable {
[super startWithWriteable:writeable];
// Break retain cycles.
_responseWriteable = nil;
}
@end
@implementation GRPCProtoCall
@end
/**
* Generate an NSError object that represents a failure in parsing a proto class.
*/
NSError *ErrorForBadProto(id proto, Class expectedClass, NSError *parsingError) {
NSDictionary *info = @{
NSLocalizedDescriptionKey : @"Unable to parse response from the server",
NSLocalizedRecoverySuggestionErrorKey :
@"If this RPC is idempotent, retry "
@"with exponential backoff. Otherwise, query the server status before "
@"retrying.",
NSUnderlyingErrorKey : parsingError,
@"Expected class" : expectedClass,
@"Received value" : proto,
};
// TODO(jcanizales): Use kGRPCErrorDomain and GRPCErrorCodeInternal when they're public.
return [NSError errorWithDomain:@"io.grpc" code:13 userInfo:info];
}

@ -26,6 +26,7 @@
@class GRPCUnaryProtoCall;
@class GRPCStreamingProtoCall;
@protocol GRPCProtoResponseHandler;
@protocol GRXWriteable;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability-completeness"
@ -38,15 +39,6 @@ __attribute__((deprecated("Please use GRPCProtoService."))) @interface ProtoServ
: (nonnull NSString *)packageName serviceName : (nonnull NSString *)serviceName callOptions
: (nullable GRPCCallOptions *)callOptions NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithHost:(NSString *)host
packageName:(NSString *)packageName
serviceName:(NSString *)serviceName;
- (GRPCProtoCall *)RPCToMethod:(NSString *)method
requestsWriter:(GRXWriter *)requestsWriter
responseClass:(Class)responseClass
responsesWriteable:(id<GRXWriteable>)responsesWriteable;
- (nullable GRPCUnaryProtoCall *)RPCToMethod:(nonnull NSString *)method
message:(nonnull id)message
responseHandler:(nonnull id<GRPCProtoResponseHandler>)handler
@ -58,6 +50,18 @@ __attribute__((deprecated("Please use GRPCProtoService."))) @interface ProtoServ
callOptions:(nullable GRPCCallOptions *)callOptions
responseClass:(nonnull Class)responseClass;
@end
@interface ProtoService(Legacy)
- (instancetype)initWithHost : (NSString *)host packageName
: (NSString *)packageName serviceName : (NSString *)serviceName;
- (GRPCProtoCall *)RPCToMethod:(NSString *)method
requestsWriter:(GRXWriter *)requestsWriter
responseClass:(Class)responseClass
responsesWriteable:(id<GRXWriteable>)responsesWriteable;
@end
#pragma clang diagnostic pop

@ -29,15 +29,21 @@
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
@implementation ProtoService {
#pragma clang diagnostic pop
GRPCCallOptions *_callOptions;
NSString *_host;
NSString *_packageName;
NSString *_serviceName;
GRPCCallOptions *_callOptions;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
// Do not call the default init method
- (instancetype)init {
return [self initWithHost:nil packageName:nil serviceName:nil];
[NSException raise:NSGenericException format:@"Do not call init method of ProtoService"];
return [self initWithHost:nil packageName:nil serviceName:nil callOptions:nil];
}
#pragma clang diagnostic pop
// Designated initializer
- (instancetype)initWithHost:(NSString *)host
@ -58,38 +64,6 @@
return self;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
// Do not call designated initializer here due to nullability incompatibility. This method is from
// old API and does not assert on nullability of the parameters.
- (instancetype)initWithHost:(NSString *)host
packageName:(NSString *)packageName
serviceName:(NSString *)serviceName {
if ((self = [super init])) {
_host = [host copy];
_packageName = [packageName copy];
_serviceName = [serviceName copy];
_callOptions = nil;
}
return self;
}
#pragma clang diagnostic pop
- (GRPCProtoCall *)RPCToMethod:(NSString *)method
requestsWriter:(GRXWriter *)requestsWriter
responseClass:(Class)responseClass
responsesWriteable:(id<GRXWriteable>)responsesWriteable {
GRPCProtoMethod *methodName =
[[GRPCProtoMethod alloc] initWithPackage:_packageName service:_serviceName method:method];
return [[GRPCProtoCall alloc] initWithHost:_host
method:methodName
requestsWriter:requestsWriter
responseClass:responseClass
responsesWriteable:responsesWriteable];
}
- (GRPCUnaryProtoCall *)RPCToMethod:(NSString *)method
message:(id)message
responseHandler:(id<GRPCProtoResponseHandler>)handler

@ -0,0 +1,23 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "ProtoService.h"
@class GRPCProtoCall;
@class GRXWriter;
@protocol GRXWriteable;

@ -0,0 +1,71 @@
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import <objc/runtime.h>
#import "ProtoMethod.h"
#import "ProtoRPCLegacy.h"
#import "ProtoService.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
@implementation ProtoService (Legacy)
#pragma clang diagnostic pop
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
// Do not call designated initializer here due to nullability incompatibility. This method is from
// old API and does not assert on nullability of the parameters.
- (instancetype)initWithHost:(NSString *)host
packageName:(NSString *)packageName
serviceName:(NSString *)serviceName {
if ((self = [super init])) {
Ivar hostIvar = class_getInstanceVariable([ProtoService class], "_host");
Ivar packageNameIvar = class_getInstanceVariable([ProtoService class], "_packageName");
Ivar serviceNameIvar = class_getInstanceVariable([ProtoService class], "_serviceName");
object_setIvar(self, hostIvar, [host copy]);
object_setIvar(self, packageNameIvar, [packageName copy]);
object_setIvar(self, serviceNameIvar, [serviceName copy]);
}
return self;
}
#pragma clang diagnostic pop
- (GRPCProtoCall *)RPCToMethod:(NSString *)method
requestsWriter:(GRXWriter *)requestsWriter
responseClass:(Class)responseClass
responsesWriteable:(id<GRXWriteable>)responsesWriteable {
Ivar hostIvar = class_getInstanceVariable([ProtoService class], "_host");
Ivar packageNameIvar = class_getInstanceVariable([ProtoService class], "_packageName");
Ivar serviceNameIvar = class_getInstanceVariable([ProtoService class], "_serviceName");
NSString *host = object_getIvar(self, hostIvar);
NSString *packageName = object_getIvar(self, packageNameIvar);
NSString *serviceName = object_getIvar(self, serviceNameIvar);
GRPCProtoMethod *methodName =
[[GRPCProtoMethod alloc] initWithPackage:packageName service:serviceName method:method];
return [[GRPCProtoCall alloc] initWithHost:host
method:methodName
requestsWriter:requestsWriter
responseClass:responseClass
responsesWriteable:responsesWriteable];
}
@end

@ -25,6 +25,8 @@
#import "src/objective-c/examples/RemoteTestClient/Messages.pbobjc.h"
#import "src/objective-c/examples/RemoteTestClient/Test.pbrpc.h"
#endif
#import <GRPCClient/GRPCCallOptions.h>
#import <ProtoRPC/ProtoRPC.h>
@interface ViewController ()<GRPCProtoResponseHandler>

@ -24,6 +24,8 @@
#import "src/objective-c/examples/RemoteTestClient/Messages.pbobjc.h"
#import "src/objective-c/examples/RemoteTestClient/Test.pbrpc.h"
#endif
#import <GRPCClient/GRPCCallOptions.h>
#import <ProtoRPC/ProtoRPC.h>
@interface InterfaceController ()<GRPCProtoResponseHandler>

@ -63,9 +63,6 @@ grpc_objc_testing_library(
data = [":TestCertificates"],
defines = [
"DEBUG=1",
"PB_FIELD_32BIT=1",
"PB_NO_PACKED_STRUCTS=1",
"PB_ENABLE_MALLOC=1",
"HOST_PORT_LOCALSSL=localhost:5051",
"HOST_PORT_LOCAL=localhost:5050",
"HOST_PORT_REMOTE=grpc-test.sandbox.googleapis.com",
@ -98,19 +95,12 @@ tvos_application(
deps = ["host-lib"],
)
grpc_objc_testing_library(
name = "CronetConfig",
srcs = ["ConfigureCronet.m"],
hdrs = ["ConfigureCronet.h"],
)
grpc_objc_testing_library(
name = "InteropTests-lib",
hdrs = ["InteropTests/InteropTests.h"],
srcs = ["InteropTests/InteropTests.m"],
deps = [
":InteropTestsBlockCallbacks-lib",
":CronetConfig",
],
)
@ -203,7 +193,6 @@ ios_unit_test(
":InteropTestsRemote-lib",
":InteropTestsLocalSSL-lib",
":InteropTestsLocalCleartext-lib",
# ":InteropTestsMulitpleChannels-lib", # needs Cronet
],
test_host = ":ios-host",
)

@ -16,8 +16,6 @@
*
*/
#ifdef GRPC_COMPILE_WITH_CRONET
#ifdef __cplusplus
extern "C" {
#endif
@ -30,5 +28,3 @@ void configureCronet(void);
#ifdef __cplusplus
}
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save