diff --git a/BUILD b/BUILD index 0298f22bc82..7941edf3c42 100644 --- a/BUILD +++ b/BUILD @@ -291,6 +291,7 @@ GRPC_PUBLIC_HDRS = [ "include/grpc/grpc_posix.h", "include/grpc/grpc_security.h", "include/grpc/grpc_security_constants.h", + "include/grpc/passive_listener.h", "include/grpc/slice.h", "include/grpc/slice_buffer.h", "include/grpc/status.h", @@ -452,6 +453,7 @@ GRPCXX_PUBLIC_HDRS = [ "include/grpcpp/impl/service_type.h", "include/grpcpp/impl/status.h", "include/grpcpp/impl/sync.h", + "include/grpcpp/passive_listener.h", "include/grpcpp/resource_quota.h", "include/grpcpp/security/audit_logging.h", "include/grpcpp/security/tls_crl_provider.h", @@ -876,7 +878,7 @@ grpc_cc_library( grpc_cc_library( name = "grpc_public_hdrs", - hdrs = GRPC_PUBLIC_HDRS, + hdrs = GRPC_PUBLIC_HDRS + GRPC_PUBLIC_EVENT_ENGINE_HDRS, external_deps = [ "absl/status:statusor", "absl/strings", @@ -1243,6 +1245,7 @@ grpc_cc_library( "gpr", "grpc++_base_unsecure", "grpc++_codegen_proto", + "grpc_core_credentials_header", "grpc_public_hdrs", "grpc_security_base", "grpc_unsecure", @@ -2267,6 +2270,7 @@ grpc_cc_library( "exec_ctx", "gpr", "grpc_base", + "grpc_core_credentials_header", "grpc_public_hdrs", "grpc_trace", "handshaker", @@ -2328,6 +2332,14 @@ grpc_cc_library( ], ) +# TODO(hork): split credentials types into their own source files and targets. +grpc_cc_library( + name = "grpc_core_credentials_header", + hdrs = ["include/grpc/credentials.h"], + language = "c++", + visibility = ["@grpc:core_credentials"], +) + grpc_cc_library( name = "alts_util", srcs = [ @@ -2355,6 +2367,7 @@ grpc_cc_library( deps = [ "alts_upb", "gpr", + "grpc_core_credentials_header", "grpc_public_hdrs", ], ) @@ -2428,6 +2441,7 @@ grpc_cc_library( "grpc", "grpc++_codegen_proto", "grpc_base", + "grpc_core_credentials_header", "grpc_credentials_util", "grpc_health_upb", "grpc_public_hdrs", @@ -2458,6 +2472,7 @@ grpc_cc_library( "//src/core:grpc_backend_metric_provider", "//src/core:grpc_crl_provider", "//src/core:grpc_service_config", + "//src/core:grpc_transport_chttp2_server", "//src/core:grpc_transport_inproc", "//src/core:json", "//src/core:json_reader", @@ -2509,11 +2524,13 @@ grpc_cc_library( "exec_ctx", "gpr", "grpc_base", + "grpc_core_credentials_header", "grpc_health_upb", "grpc_public_hdrs", "grpc_security_base", "grpc_service_config_impl", "grpc_trace", + "grpc_transport_chttp2", "grpc_unsecure", "grpcpp_backend_metric_recorder", "grpcpp_call_metric_recorder", @@ -2535,6 +2552,7 @@ grpc_cc_library( "//src/core:grpc_backend_metric_provider", "//src/core:grpc_insecure_credentials", "//src/core:grpc_service_config", + "//src/core:grpc_transport_chttp2_server", "//src/core:grpc_transport_inproc", "//src/core:ref_counted", "//src/core:resource_quota", @@ -3860,6 +3878,7 @@ grpc_cc_library( "exec_ctx", "gpr", "grpc_base", + "grpc_core_credentials_header", "grpc_public_hdrs", "grpc_security_base", "handshaker", @@ -3929,6 +3948,7 @@ grpc_cc_library( "exec_ctx", "gpr", "grpc_base", + "grpc_core_credentials_header", "grpc_credentials_util", "grpc_security_base", "grpc_trace", @@ -4017,6 +4037,7 @@ grpc_cc_library( "exec_ctx", "gpr", "grpc_base", + "grpc_core_credentials_header", "grpc_security_base", "tsi_alts_frame_protector", "tsi_base", @@ -4134,6 +4155,7 @@ grpc_cc_library( "config_vars", "gpr", "grpc_base", + "grpc_core_credentials_header", "grpc_credentials_util", "grpc_public_hdrs", "grpc_security_base", diff --git a/CMakeLists.txt b/CMakeLists.txt index b8ea2f99e2f..131121baa1a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2694,6 +2694,7 @@ foreach(_hdr include/grpc/byte_buffer_reader.h include/grpc/census.h include/grpc/compression.h + include/grpc/credentials.h include/grpc/event_engine/endpoint_config.h include/grpc/event_engine/event_engine.h include/grpc/event_engine/extensible.h @@ -2741,6 +2742,7 @@ foreach(_hdr include/grpc/impl/propagation_bits.h include/grpc/impl/slice_type.h include/grpc/load_reporting.h + include/grpc/passive_listener.h include/grpc/slice.h include/grpc/slice_buffer.h include/grpc/status.h @@ -3395,6 +3397,7 @@ foreach(_hdr include/grpc/byte_buffer_reader.h include/grpc/census.h include/grpc/compression.h + include/grpc/credentials.h include/grpc/event_engine/endpoint_config.h include/grpc/event_engine/event_engine.h include/grpc/event_engine/extensible.h @@ -3442,6 +3445,7 @@ foreach(_hdr include/grpc/impl/propagation_bits.h include/grpc/impl/slice_type.h include/grpc/load_reporting.h + include/grpc/passive_listener.h include/grpc/slice.h include/grpc/slice_buffer.h include/grpc/status.h @@ -4311,6 +4315,7 @@ foreach(_hdr include/grpcpp/impl/service_type.h include/grpcpp/impl/status.h include/grpcpp/impl/sync.h + include/grpcpp/passive_listener.h include/grpcpp/resource_quota.h include/grpcpp/security/audit_logging.h include/grpcpp/security/auth_context.h @@ -5051,6 +5056,7 @@ foreach(_hdr include/grpcpp/impl/service_type.h include/grpcpp/impl/status.h include/grpcpp/impl/sync.h + include/grpcpp/passive_listener.h include/grpcpp/resource_quota.h include/grpcpp/security/audit_logging.h include/grpcpp/security/auth_context.h @@ -5452,6 +5458,7 @@ foreach(_hdr include/grpc/byte_buffer.h include/grpc/byte_buffer_reader.h include/grpc/compression.h + include/grpc/credentials.h include/grpc/event_engine/endpoint_config.h include/grpc/event_engine/event_engine.h include/grpc/event_engine/extensible.h @@ -5499,6 +5506,7 @@ foreach(_hdr include/grpc/impl/propagation_bits.h include/grpc/impl/slice_type.h include/grpc/load_reporting.h + include/grpc/passive_listener.h include/grpc/slice.h include/grpc/slice_buffer.h include/grpc/status.h @@ -7760,6 +7768,7 @@ target_include_directories(bad_streaming_id_bad_client_test target_link_libraries(bad_streaming_id_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -7804,6 +7813,7 @@ target_include_directories(badreq_bad_client_test target_link_libraries(badreq_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -11391,6 +11401,7 @@ target_include_directories(connection_prefix_bad_client_test target_link_libraries(connection_prefix_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -12448,6 +12459,7 @@ target_include_directories(duplicate_header_bad_client_test target_link_libraries(duplicate_header_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -16516,6 +16528,7 @@ target_include_directories(head_of_line_blocking_bad_client_test target_link_libraries(head_of_line_blocking_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -16560,6 +16573,7 @@ target_include_directories(headers_bad_client_test target_link_libraries(headers_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -17557,6 +17571,7 @@ target_include_directories(initial_settings_frame_bad_client_test target_link_libraries(initial_settings_frame_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -20785,6 +20800,7 @@ target_include_directories(out_of_bounds_bad_client_test target_link_libraries(out_of_bounds_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -26659,6 +26675,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/xds/v3/orca_load_report.grpc.pb.cc ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/xds/v3/orca_load_report.pb.h ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/testing/xds/v3/orca_load_report.grpc.pb.h + test/core/event_engine/event_engine_test_utils.cc test/core/util/cmdline.cc test/core/util/fuzzer_util.cc test/core/util/grpc_profiler.cc @@ -26703,6 +26720,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) target_link_libraries(server_builder_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc++_unsecure grpc_test_util_unsecure ) @@ -27174,6 +27192,7 @@ target_include_directories(server_registered_method_bad_client_test target_link_libraries(server_registered_method_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -27919,6 +27938,7 @@ target_include_directories(simple_request_bad_client_test target_link_libraries(simple_request_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -29981,6 +30001,7 @@ target_include_directories(test_core_security_credentials_test target_link_libraries(test_core_security_credentials_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -31823,6 +31844,7 @@ target_include_directories(unknown_frame_bad_client_test target_link_libraries(unknown_frame_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) @@ -32297,6 +32319,7 @@ target_include_directories(window_overflow_bad_client_test target_link_libraries(window_overflow_bad_client_test ${_gRPC_ALLTARGETS_LIBRARIES} gtest + absl::check grpc_test_util ) diff --git a/Makefile b/Makefile index ac23dd86dc3..5a7f90db9cc 100644 --- a/Makefile +++ b/Makefile @@ -1728,6 +1728,7 @@ PUBLIC_HEADERS_C += \ include/grpc/byte_buffer_reader.h \ include/grpc/census.h \ include/grpc/compression.h \ + include/grpc/credentials.h \ include/grpc/event_engine/endpoint_config.h \ include/grpc/event_engine/event_engine.h \ include/grpc/event_engine/extensible.h \ @@ -1775,6 +1776,7 @@ PUBLIC_HEADERS_C += \ include/grpc/impl/propagation_bits.h \ include/grpc/impl/slice_type.h \ include/grpc/load_reporting.h \ + include/grpc/passive_listener.h \ include/grpc/slice.h \ include/grpc/slice_buffer.h \ include/grpc/status.h \ diff --git a/Package.swift b/Package.swift index 651d0d3822c..22f0e7cac9f 100644 --- a/Package.swift +++ b/Package.swift @@ -45,6 +45,7 @@ let package = Package( "include/grpc/byte_buffer_reader.h", "include/grpc/census.h", "include/grpc/compression.h", + "include/grpc/credentials.h", "include/grpc/event_engine/endpoint_config.h", "include/grpc/event_engine/event_engine.h", "include/grpc/event_engine/extensible.h", @@ -92,6 +93,7 @@ let package = Package( "include/grpc/impl/propagation_bits.h", "include/grpc/impl/slice_type.h", "include/grpc/load_reporting.h", + "include/grpc/passive_listener.h", "include/grpc/slice.h", "include/grpc/slice_buffer.h", "include/grpc/status.h", diff --git a/bazel/experiments.bzl b/bazel/experiments.bzl index 0e5f00b71eb..e366840a1e6 100644 --- a/bazel/experiments.bzl +++ b/bazel/experiments.bzl @@ -25,6 +25,7 @@ EXPERIMENT_ENABLES = { "event_engine_dns": "event_engine_dns", "event_engine_listener": "event_engine_listener", "free_large_allocator": "free_large_allocator", + "http2_stats_fix": "http2_stats_fix", "keepalive_fix": "keepalive_fix", "keepalive_server_fix": "keepalive_server_fix", "monitoring_experiment": "monitoring_experiment", diff --git a/bazel/grpc_build_system.bzl b/bazel/grpc_build_system.bzl index 1da3bac40ab..54bb074ab2e 100644 --- a/bazel/grpc_build_system.bzl +++ b/bazel/grpc_build_system.bzl @@ -102,6 +102,7 @@ def _update_visibility(visibility): "chaotic_good": PRIVATE, "client_channel": PRIVATE, "cli": PRIVATE, + "core_credentials": PRIVATE, "debug_location": PRIVATE, "endpoint_tests": PRIVATE, "exec_ctx": PRIVATE, @@ -116,6 +117,7 @@ def _update_visibility(visibility): "iomgr_internal_errqueue": PRIVATE, "iomgr_buffer_list": PRIVATE, "json_reader_legacy": PRIVATE, + "otel_plugin": PRIVATE, "public": PUBLIC, "ref_counted_ptr": PRIVATE, "tcp_tracer": PRIVATE, diff --git a/build_autogenerated.yaml b/build_autogenerated.yaml index 6716d165cec..0a699c30309 100644 --- a/build_autogenerated.yaml +++ b/build_autogenerated.yaml @@ -149,6 +149,7 @@ libs: - include/grpc/byte_buffer_reader.h - include/grpc/census.h - include/grpc/compression.h + - include/grpc/credentials.h - include/grpc/event_engine/endpoint_config.h - include/grpc/event_engine/event_engine.h - include/grpc/event_engine/extensible.h @@ -196,6 +197,7 @@ libs: - include/grpc/impl/propagation_bits.h - include/grpc/impl/slice_type.h - include/grpc/load_reporting.h + - include/grpc/passive_listener.h - include/grpc/slice.h - include/grpc/slice_buffer.h - include/grpc/status.h @@ -2136,6 +2138,7 @@ libs: - include/grpc/byte_buffer_reader.h - include/grpc/census.h - include/grpc/compression.h + - include/grpc/credentials.h - include/grpc/event_engine/endpoint_config.h - include/grpc/event_engine/event_engine.h - include/grpc/event_engine/extensible.h @@ -2183,6 +2186,7 @@ libs: - include/grpc/impl/propagation_bits.h - include/grpc/impl/slice_type.h - include/grpc/load_reporting.h + - include/grpc/passive_listener.h - include/grpc/slice.h - include/grpc/slice_buffer.h - include/grpc/status.h @@ -3793,6 +3797,7 @@ libs: - include/grpcpp/impl/service_type.h - include/grpcpp/impl/status.h - include/grpcpp/impl/sync.h + - include/grpcpp/passive_listener.h - include/grpcpp/resource_quota.h - include/grpcpp/security/audit_logging.h - include/grpcpp/security/auth_context.h @@ -4221,6 +4226,7 @@ libs: - include/grpcpp/impl/service_type.h - include/grpcpp/impl/status.h - include/grpcpp/impl/sync.h + - include/grpcpp/passive_listener.h - include/grpcpp/resource_quota.h - include/grpcpp/security/audit_logging.h - include/grpcpp/security/auth_context.h @@ -4321,6 +4327,7 @@ libs: - include/grpc/byte_buffer.h - include/grpc/byte_buffer_reader.h - include/grpc/compression.h + - include/grpc/credentials.h - include/grpc/event_engine/endpoint_config.h - include/grpc/event_engine/event_engine.h - include/grpc/event_engine/extensible.h @@ -4368,6 +4375,7 @@ libs: - include/grpc/impl/propagation_bits.h - include/grpc/impl/slice_type.h - include/grpc/load_reporting.h + - include/grpc/passive_listener.h - include/grpc/slice.h - include/grpc/slice_buffer.h - include/grpc/status.h @@ -5973,6 +5981,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: badreq_bad_client_test gtest: true @@ -5987,6 +5996,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: basic_work_queue_test gtest: true @@ -8270,6 +8280,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: connection_refused_test gtest: true @@ -8723,6 +8734,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: empty_batch_test gtest: true @@ -10999,6 +11011,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: headers_bad_client_test gtest: true @@ -11013,6 +11026,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: health_service_end2end_test gtest: true @@ -11517,6 +11531,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: inproc_test gtest: true @@ -13363,6 +13378,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: outlier_detection_lb_config_parser_test gtest: true @@ -17380,6 +17396,7 @@ targets: build: test language: c++ headers: + - test/core/event_engine/event_engine_test_utils.h - test/core/util/cmdline.h - test/core/util/evaluate_args_test_util.h - test/core/util/fuzzer_util.h @@ -17396,6 +17413,7 @@ targets: - src/proto/grpc/testing/echo_messages.proto - src/proto/grpc/testing/simple_messages.proto - src/proto/grpc/testing/xds/v3/orca_load_report.proto + - test/core/event_engine/event_engine_test_utils.cc - test/core/util/cmdline.cc - test/core/util/fuzzer_util.cc - test/core/util/grpc_profiler.cc @@ -17408,6 +17426,7 @@ targets: - test/cpp/server/server_builder_test.cc deps: - gtest + - absl/log:check - grpc++_unsecure - grpc_test_util_unsecure platforms: @@ -17605,6 +17624,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: server_request_call_test gtest: true @@ -18079,6 +18099,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: simple_request_test gtest: true @@ -19024,6 +19045,7 @@ targets: - test/core/util/tracer_util.cc deps: - gtest + - absl/log:check - grpc_test_util - name: test_core_security_ssl_credentials_test gtest: true @@ -19856,6 +19878,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: uri_parser_test gtest: true @@ -20021,6 +20044,7 @@ targets: - test/core/end2end/cq_verifier.cc deps: - gtest + - absl/log:check - grpc_test_util - name: windows_endpoint_test gtest: true diff --git a/examples/cpp/csm/BUILD b/examples/cpp/csm/BUILD index 836abbab310..7f1bf30d836 100644 --- a/examples/cpp/csm/BUILD +++ b/examples/cpp/csm/BUILD @@ -41,6 +41,7 @@ cc_binary( "//examples/protos:helloworld_cc_grpc", "@com_google_absl//absl/flags:flag", "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/log", "@io_opentelemetry_cpp//exporters/prometheus:prometheus_exporter", "@io_opentelemetry_cpp//sdk/src/metrics", ], diff --git a/examples/cpp/csm/csm_greeter_server.cc b/examples/cpp/csm/csm_greeter_server.cc index c5d7857e7fa..910e3f65749 100644 --- a/examples/cpp/csm/csm_greeter_server.cc +++ b/examples/cpp/csm/csm_greeter_server.cc @@ -22,6 +22,7 @@ #include "absl/flags/flag.h" #include "absl/flags/parse.h" +#include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "opentelemetry/exporters/prometheus/exporter_factory.h" #include "opentelemetry/exporters/prometheus/exporter_options.h" @@ -91,7 +92,7 @@ void RunServer(const char* hostname) { xds_builder.AddListeningPort(absl::StrCat("0.0.0.0:", port), grpc::InsecureServerCredentials()); xds_enabled_server = xds_builder.BuildAndStart(); - gpr_log(GPR_INFO, "Server starting on 0.0.0.0:%d", port); + LOG(INFO) << "Server starting on 0.0.0.0:" << port; // Wait for the server to shutdown. Note that some other thread must be // responsible for shutting down the server for this call to ever return. diff --git a/examples/cpp/helloworld/BUILD b/examples/cpp/helloworld/BUILD index 3c01b6ce1c3..1bcee389efb 100644 --- a/examples/cpp/helloworld/BUILD +++ b/examples/cpp/helloworld/BUILD @@ -129,5 +129,6 @@ cc_binary( "//examples/protos:helloworld_cc_grpc", "@com_google_absl//absl/flags:flag", "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/log", ], ) diff --git a/examples/cpp/helloworld/CMakeLists.txt b/examples/cpp/helloworld/CMakeLists.txt index 73ad4877483..defe3064b14 100644 --- a/examples/cpp/helloworld/CMakeLists.txt +++ b/examples/cpp/helloworld/CMakeLists.txt @@ -68,6 +68,7 @@ foreach(_target absl::check absl::flags absl::flags_parse + absl::log ${_REFLECTION} ${_GRPC_GRPCPP} ${_PROTOBUF_LIBPROTOBUF}) diff --git a/examples/cpp/helloworld/xds_greeter_server.cc b/examples/cpp/helloworld/xds_greeter_server.cc index 9e4ca2a0549..c0bed68ff7a 100644 --- a/examples/cpp/helloworld/xds_greeter_server.cc +++ b/examples/cpp/helloworld/xds_greeter_server.cc @@ -22,6 +22,7 @@ #include "absl/flags/flag.h" #include "absl/flags/parse.h" +#include "absl/log/log.h" #include "absl/strings/str_cat.h" #include @@ -79,21 +80,20 @@ void RunServer() { absl::StrCat("0.0.0.0:", port), grpc::XdsServerCredentials(grpc::InsecureServerCredentials())); xds_enabled_server = xds_builder.BuildAndStart(); - gpr_log(GPR_INFO, "Server starting on 0.0.0.0:%d", port); + LOG(INFO) << "Server starting on 0.0.0.0:" << port; grpc::AddAdminServices(&builder); // For the maintenance server, do not use any authentication mechanism. builder.AddListeningPort(absl::StrCat("0.0.0.0:", maintenance_port), grpc::InsecureServerCredentials()); server = builder.BuildAndStart(); - gpr_log(GPR_INFO, "Maintenance server listening on 0.0.0.0:%d", - maintenance_port); + LOG(INFO) << "Maintenance server listening on 0.0.0.0:" << maintenance_port; } else { grpc::AddAdminServices(&xds_builder); // Listen on the given address without any authentication mechanism. builder.AddListeningPort(absl::StrCat("0.0.0.0:", port), grpc::InsecureServerCredentials()); server = xds_builder.BuildAndStart(); - gpr_log(GPR_INFO, "Server listening on 0.0.0.0:%d", port); + LOG(INFO) << "Server listening on 0.0.0.0:" << port; } // Wait for the server to shutdown. Note that some other thread must be diff --git a/examples/cpp/keepalive/CMakeLists.txt b/examples/cpp/keepalive/CMakeLists.txt index 06024dfbc9b..8053fba1df6 100644 --- a/examples/cpp/keepalive/CMakeLists.txt +++ b/examples/cpp/keepalive/CMakeLists.txt @@ -58,7 +58,7 @@ target_link_libraries(hw_grpc_proto # Targets greeter_[async_](client|server) foreach(_target - greeter_callback_client greeter_callback_server + greeter_callback_client greeter_callback_server) add_executable(${_target} "${_target}.cc") target_link_libraries(${_target} hw_grpc_proto diff --git a/examples/cpp/xds/BUILD b/examples/cpp/xds/BUILD index 6657b1cbbf6..bf5abfd1807 100644 --- a/examples/cpp/xds/BUILD +++ b/examples/cpp/xds/BUILD @@ -37,5 +37,6 @@ cc_binary( "//examples/protos:helloworld_cc_grpc", "@com_google_absl//absl/flags:flag", "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/log", ], ) diff --git a/examples/cpp/xds/xds_greeter_server.cc b/examples/cpp/xds/xds_greeter_server.cc index bc4fe66c0f5..c35166c819e 100644 --- a/examples/cpp/xds/xds_greeter_server.cc +++ b/examples/cpp/xds/xds_greeter_server.cc @@ -22,6 +22,7 @@ #include "absl/flags/flag.h" #include "absl/flags/parse.h" +#include "absl/log/log.h" #include "absl/strings/str_cat.h" #include @@ -84,21 +85,20 @@ void RunServer() { absl::StrCat("0.0.0.0:", port), grpc::XdsServerCredentials(grpc::InsecureServerCredentials())); xds_enabled_server = xds_builder.BuildAndStart(); - gpr_log(GPR_INFO, "Server starting on 0.0.0.0:%d", port); + LOG(INFO) << "Server starting on 0.0.0.0:" << port; grpc::AddAdminServices(&builder); // For the maintenance server, do not use any authentication mechanism. builder.AddListeningPort(absl::StrCat("0.0.0.0:", maintenance_port), grpc::InsecureServerCredentials()); server = builder.BuildAndStart(); - gpr_log(GPR_INFO, "Maintenance server listening on 0.0.0.0:%d", - maintenance_port); + LOG(INFO) << "Maintenance server listening on 0.0.0.0:" << maintenance_port; } else { grpc::AddAdminServices(&xds_builder); // Listen on the given address without any authentication mechanism. builder.AddListeningPort(absl::StrCat("0.0.0.0:", port), grpc::InsecureServerCredentials()); server = xds_builder.BuildAndStart(); - gpr_log(GPR_INFO, "Server listening on 0.0.0.0:%d", port); + LOG(INFO) << "Server listening on 0.0.0.0:" << port; } // Wait for the server to shutdown. Note that some other thread must be diff --git a/gRPC-C++.podspec b/gRPC-C++.podspec index 9114af3c0d9..0ac465034a2 100644 --- a/gRPC-C++.podspec +++ b/gRPC-C++.podspec @@ -175,6 +175,7 @@ Pod::Spec.new do |s| 'include/grpcpp/impl/service_type.h', 'include/grpcpp/impl/status.h', 'include/grpcpp/impl/sync.h', + 'include/grpcpp/passive_listener.h', 'include/grpcpp/resource_quota.h', 'include/grpcpp/security/audit_logging.h', 'include/grpcpp/security/auth_context.h', diff --git a/gRPC-Core.podspec b/gRPC-Core.podspec index 46f43b36dfb..b711dd5bc02 100644 --- a/gRPC-Core.podspec +++ b/gRPC-Core.podspec @@ -119,6 +119,7 @@ Pod::Spec.new do |s| 'include/grpc/byte_buffer_reader.h', 'include/grpc/census.h', 'include/grpc/compression.h', + 'include/grpc/credentials.h', 'include/grpc/event_engine/endpoint_config.h', 'include/grpc/event_engine/event_engine.h', 'include/grpc/event_engine/extensible.h', @@ -166,6 +167,7 @@ Pod::Spec.new do |s| 'include/grpc/impl/propagation_bits.h', 'include/grpc/impl/slice_type.h', 'include/grpc/load_reporting.h', + 'include/grpc/passive_listener.h', 'include/grpc/slice.h', 'include/grpc/slice_buffer.h', 'include/grpc/status.h', diff --git a/grpc.def b/grpc.def index 41ad2dd61df..154e8eee94d 100644 --- a/grpc.def +++ b/grpc.def @@ -19,6 +19,70 @@ EXPORTS grpc_compression_options_enable_algorithm grpc_compression_options_disable_algorithm grpc_compression_options_is_algorithm_enabled + grpc_service_account_jwt_access_credentials_create + grpc_external_account_credentials_create + grpc_google_refresh_token_credentials_create + grpc_access_token_credentials_create + grpc_google_iam_credentials_create + grpc_sts_credentials_create + grpc_auth_metadata_context_copy + grpc_auth_metadata_context_reset + grpc_metadata_credentials_create_from_plugin + grpc_call_credentials_release + grpc_google_default_credentials_create + grpc_ssl_server_certificate_config_create + grpc_ssl_server_certificate_config_destroy + grpc_ssl_credentials_create + grpc_ssl_credentials_create_ex + grpc_ssl_server_credentials_create + grpc_ssl_server_credentials_create_ex + grpc_ssl_server_credentials_create_options_using_config + grpc_ssl_server_credentials_create_options_using_config_fetcher + grpc_ssl_server_credentials_options_destroy + grpc_ssl_server_credentials_create_with_options + grpc_server_credentials_set_auth_metadata_processor + grpc_composite_call_credentials_create + grpc_google_compute_engine_credentials_create + grpc_composite_channel_credentials_create + grpc_alts_credentials_client_options_create + grpc_alts_credentials_server_options_create + grpc_alts_credentials_client_options_add_target_service_account + grpc_alts_credentials_options_destroy + grpc_alts_credentials_create + grpc_alts_server_credentials_create + grpc_tls_identity_pairs_create + grpc_tls_identity_pairs_add_pair + grpc_tls_identity_pairs_destroy + grpc_tls_certificate_provider_static_data_create + grpc_tls_certificate_provider_file_watcher_create + grpc_tls_certificate_provider_release + grpc_tls_credentials_options_create + grpc_tls_credentials_options_set_min_tls_version + grpc_tls_credentials_options_set_max_tls_version + grpc_tls_credentials_options_copy + grpc_tls_credentials_options_destroy + grpc_tls_credentials_options_set_certificate_provider + grpc_tls_credentials_options_watch_root_certs + grpc_tls_credentials_options_set_root_cert_name + grpc_tls_credentials_options_watch_identity_key_cert_pairs + grpc_tls_credentials_options_set_identity_cert_name + grpc_tls_credentials_options_set_cert_request_type + grpc_tls_credentials_options_set_crl_directory + grpc_tls_credentials_options_set_verify_server_cert + grpc_tls_credentials_options_set_send_client_ca_list + grpc_ssl_session_cache_create_lru + grpc_ssl_session_cache_destroy + grpc_ssl_session_cache_create_channel_arg + grpc_set_ssl_roots_override_callback + grpc_max_auth_token_lifetime + grpc_insecure_credentials_create + grpc_insecure_server_credentials_create + grpc_xds_credentials_create + grpc_xds_server_credentials_create + grpc_local_credentials_create + grpc_local_server_credentials_create + grpc_tls_credentials_options_set_check_call_host + grpc_tls_credentials_options_set_tls_session_key_log_file_path grpc_metadata_array_init grpc_metadata_array_destroy grpc_call_details_init @@ -64,6 +128,7 @@ EXPORTS grpc_call_failed_before_recv_message grpc_call_ref grpc_call_unref + grpc_call_set_credentials grpc_server_request_call grpc_server_register_method grpc_server_request_registered_call @@ -110,74 +175,9 @@ EXPORTS grpc_auth_context_add_property grpc_auth_context_add_cstring_property grpc_auth_context_set_peer_identity_property_name - grpc_ssl_session_cache_create_lru - grpc_ssl_session_cache_destroy - grpc_ssl_session_cache_create_channel_arg - grpc_call_credentials_release - grpc_google_default_credentials_create - grpc_set_ssl_roots_override_callback - grpc_ssl_credentials_create - grpc_ssl_credentials_create_ex - grpc_composite_channel_credentials_create - grpc_composite_call_credentials_create - grpc_google_compute_engine_credentials_create - grpc_max_auth_token_lifetime - grpc_service_account_jwt_access_credentials_create - grpc_external_account_credentials_create - grpc_google_refresh_token_credentials_create - grpc_access_token_credentials_create - grpc_google_iam_credentials_create - grpc_sts_credentials_create - grpc_auth_metadata_context_copy - grpc_auth_metadata_context_reset - grpc_metadata_credentials_create_from_plugin - grpc_ssl_server_certificate_config_create - grpc_ssl_server_certificate_config_destroy - grpc_ssl_server_credentials_create - grpc_ssl_server_credentials_create_ex - grpc_ssl_server_credentials_create_options_using_config - grpc_ssl_server_credentials_create_options_using_config_fetcher - grpc_ssl_server_credentials_options_destroy - grpc_ssl_server_credentials_create_with_options - grpc_call_set_credentials - grpc_server_credentials_set_auth_metadata_processor - grpc_alts_credentials_client_options_create - grpc_alts_credentials_server_options_create - grpc_alts_credentials_client_options_add_target_service_account - grpc_alts_credentials_options_destroy - grpc_alts_credentials_create - grpc_alts_server_credentials_create - grpc_local_credentials_create - grpc_local_server_credentials_create - grpc_tls_identity_pairs_create - grpc_tls_identity_pairs_add_pair - grpc_tls_identity_pairs_destroy - grpc_tls_certificate_provider_static_data_create - grpc_tls_certificate_provider_file_watcher_create - grpc_tls_certificate_provider_release - grpc_tls_credentials_options_create - grpc_tls_credentials_options_set_min_tls_version - grpc_tls_credentials_options_set_max_tls_version - grpc_tls_credentials_options_copy - grpc_tls_credentials_options_destroy - grpc_tls_credentials_options_set_certificate_provider - grpc_tls_credentials_options_watch_root_certs - grpc_tls_credentials_options_set_root_cert_name - grpc_tls_credentials_options_watch_identity_key_cert_pairs - grpc_tls_credentials_options_set_identity_cert_name - grpc_tls_credentials_options_set_cert_request_type - grpc_tls_credentials_options_set_crl_directory - grpc_tls_credentials_options_set_verify_server_cert - grpc_tls_credentials_options_set_send_client_ca_list - grpc_tls_credentials_options_set_check_call_host - grpc_insecure_credentials_create - grpc_insecure_server_credentials_create - grpc_xds_credentials_create - grpc_xds_server_credentials_create grpc_authorization_policy_provider_static_data_create grpc_authorization_policy_provider_file_watcher_create grpc_authorization_policy_provider_release - grpc_tls_credentials_options_set_tls_session_key_log_file_path grpc_slice_ref grpc_slice_unref grpc_slice_copy diff --git a/grpc.gemspec b/grpc.gemspec index 73b32228479..9283dd994ed 100644 --- a/grpc.gemspec +++ b/grpc.gemspec @@ -51,6 +51,7 @@ Gem::Specification.new do |s| s.files += %w( include/grpc/byte_buffer_reader.h ) s.files += %w( include/grpc/census.h ) s.files += %w( include/grpc/compression.h ) + s.files += %w( include/grpc/credentials.h ) s.files += %w( include/grpc/event_engine/endpoint_config.h ) s.files += %w( include/grpc/event_engine/event_engine.h ) s.files += %w( include/grpc/event_engine/extensible.h ) @@ -98,6 +99,7 @@ Gem::Specification.new do |s| s.files += %w( include/grpc/impl/propagation_bits.h ) s.files += %w( include/grpc/impl/slice_type.h ) s.files += %w( include/grpc/load_reporting.h ) + s.files += %w( include/grpc/passive_listener.h ) s.files += %w( include/grpc/slice.h ) s.files += %w( include/grpc/slice_buffer.h ) s.files += %w( include/grpc/status.h ) diff --git a/include/grpc/credentials.h b/include/grpc/credentials.h new file mode 100644 index 00000000000..c3a076991c6 --- /dev/null +++ b/include/grpc/credentials.h @@ -0,0 +1,1222 @@ +/* + * + * Copyright 2024 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. + * + */ + +#ifndef GRPC_CREDENTIALS_H +#define GRPC_CREDENTIALS_H + +#include + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** --- grpc_call_credentials object --- + + A call credentials object represents a way to authenticate on a particular + call. These credentials can be composed with a channel credentials object + so that they are sent with every call on this channel. */ + +typedef struct grpc_call_credentials grpc_call_credentials; +typedef struct grpc_auth_context grpc_auth_context; + +/** Creates a JWT credentials object. May return NULL if the input is invalid. + - json_key is the JSON key string containing the client's private key. + - token_lifetime is the lifetime of each Json Web Token (JWT) created with + this credentials. It should not exceed grpc_max_auth_token_lifetime or + will be cropped to this value. */ +GRPCAPI grpc_call_credentials* +grpc_service_account_jwt_access_credentials_create(const char* json_key, + gpr_timespec token_lifetime, + void* reserved); + +/** Builds External Account credentials. + - json_string is the JSON string containing the credentials options. + - scopes_string contains the scopes to be binded with the credentials. + This API is used for experimental purposes for now and may change in the + future. */ +GRPCAPI grpc_call_credentials* grpc_external_account_credentials_create( + const char* json_string, const char* scopes_string); + +/** Creates an Oauth2 Refresh Token credentials object for connecting to Google. + May return NULL if the input is invalid. + WARNING: Do NOT use this credentials to connect to a non-google service as + this could result in an oauth2 token leak. + - json_refresh_token is the JSON string containing the refresh token itself + along with a client_id and client_secret. */ +GRPCAPI grpc_call_credentials* grpc_google_refresh_token_credentials_create( + const char* json_refresh_token, void* reserved); + +/** Creates an Oauth2 Access Token credentials with an access token that was + acquired by an out of band mechanism. */ +GRPCAPI grpc_call_credentials* grpc_access_token_credentials_create( + const char* access_token, void* reserved); + +/** Creates an IAM credentials object for connecting to Google. */ +GRPCAPI grpc_call_credentials* grpc_google_iam_credentials_create( + const char* authorization_token, const char* authority_selector, + void* reserved); + +/** Options for creating STS Oauth Token Exchange credentials following the IETF + draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16. + Optional fields may be set to NULL or empty string. It is the responsibility + of the caller to ensure that the subject and actor tokens are refreshed on + disk at the specified paths. This API is used for experimental purposes for + now and may change in the future. */ +typedef struct { + const char* token_exchange_service_uri; /* Required. */ + const char* resource; /* Optional. */ + const char* audience; /* Optional. */ + const char* scope; /* Optional. */ + const char* requested_token_type; /* Optional. */ + const char* subject_token_path; /* Required. */ + const char* subject_token_type; /* Required. */ + const char* actor_token_path; /* Optional. */ + const char* actor_token_type; /* Optional. */ +} grpc_sts_credentials_options; + +/** Creates an STS credentials following the STS Token Exchanged specified in + the IETF draft + https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16. This API is + used for experimental purposes for now and may change in the future. */ +GRPCAPI grpc_call_credentials* grpc_sts_credentials_create( + const grpc_sts_credentials_options* options, void* reserved); + +/** Context that can be used by metadata credentials plugin in order to create + auth related metadata. */ +typedef struct { + /** The fully qualifed service url. */ + const char* service_url; + + /** The method name of the RPC being called (not fully qualified). + The fully qualified method name can be built from the service_url: + full_qualified_method_name = ctx->service_url + '/' + ctx->method_name. */ + const char* method_name; + + /** The auth_context of the channel which gives the server's identity. */ + const grpc_auth_context* channel_auth_context; + + /** Reserved for future use. */ + void* reserved; +} grpc_auth_metadata_context; + +/** Performs a deep copy from \a from to \a to. **/ +GRPCAPI void grpc_auth_metadata_context_copy(grpc_auth_metadata_context* from, + grpc_auth_metadata_context* to); + +/** Releases internal resources held by \a context. **/ +GRPCAPI void grpc_auth_metadata_context_reset( + grpc_auth_metadata_context* context); + +/** Callback function to be called by the metadata credentials plugin + implementation when the metadata is ready. + - user_data is the opaque pointer that was passed in the get_metadata method + of the grpc_metadata_credentials_plugin (see below). + - creds_md is an array of credentials metadata produced by the plugin. It + may be set to NULL in case of an error. + - num_creds_md is the number of items in the creds_md array. + - status must be GRPC_STATUS_OK in case of success or another specific error + code otherwise. + - error_details contains details about the error if any. In case of success + it should be NULL and will be otherwise ignored. */ +typedef void (*grpc_credentials_plugin_metadata_cb)( + void* user_data, const grpc_metadata* creds_md, size_t num_creds_md, + grpc_status_code status, const char* error_details); + +/** Maximum number of metadata entries returnable by a credentials plugin via + a synchronous return. */ +#define GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX 4 + +/** grpc_metadata_credentials plugin is an API user provided structure used to + create grpc_credentials objects that can be set on a channel (composed) or + a call. See grpc_credentials_metadata_create_from_plugin below. + The grpc client stack will call the get_metadata method of the plugin for + every call in scope for the credentials created from it. */ +typedef struct { + /** The implementation of this method has to be non-blocking, but can + be performed synchronously or asynchronously. + + If processing occurs synchronously, returns non-zero and populates + creds_md, num_creds_md, status, and error_details. In this case, + the caller takes ownership of the entries in creds_md and of + error_details. Note that if the plugin needs to return more than + GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX entries in creds_md, it must + return asynchronously. + + If processing occurs asynchronously, returns zero and invokes \a cb + when processing is completed. \a user_data will be passed as the + first parameter of the callback. NOTE: \a cb MUST be invoked in a + different thread, not from the thread in which \a get_metadata() is + invoked. + + \a context is the information that can be used by the plugin to create + auth metadata. */ + int (*get_metadata)( + void* state, grpc_auth_metadata_context context, + grpc_credentials_plugin_metadata_cb cb, void* user_data, + grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], + size_t* num_creds_md, grpc_status_code* status, + const char** error_details); + + /** Implements debug string of the given plugin. This method returns an + * allocated string that the caller needs to free using gpr_free() */ + char* (*debug_string)(void* state); + + /** Destroys the plugin state. */ + void (*destroy)(void* state); + + /** State that will be set as the first parameter of the methods above. */ + void* state; + + /** Type of credentials that this plugin is implementing. */ + const char* type; +} grpc_metadata_credentials_plugin; + +/** Creates a credentials object from a plugin with a specified minimum security + * level. */ +GRPCAPI grpc_call_credentials* grpc_metadata_credentials_create_from_plugin( + grpc_metadata_credentials_plugin plugin, + grpc_security_level min_security_level, void* reserved); + +/** --- channel credentials --- */ + +/** Releases a call credentials object. + The creator of the credentials object is responsible for its release. */ +GRPCAPI void grpc_call_credentials_release(grpc_call_credentials* creds); + +/** Creates default credentials to connect to a google gRPC service. + WARNING: Do NOT use this credentials to connect to a non-google service as + this could result in an oauth2 token leak. The security level of the + resulting connection is GRPC_PRIVACY_AND_INTEGRITY. + + If specified, the supplied call credentials object will be attached to the + returned channel credentials object. The call_credentials object must remain + valid throughout the lifetime of the returned grpc_channel_credentials + object. It is expected that the call credentials object was generated + according to the Application Default Credentials mechanism and asserts the + identity of the default service account of the machine. Supplying any other + sort of call credential will result in undefined behavior, up to and + including the sudden and unexpected failure of RPCs. + + If nullptr is supplied, the returned channel credentials object will use a + call credentials object based on the Application Default Credentials + mechanism. +*/ +GRPCAPI grpc_channel_credentials* grpc_google_default_credentials_create( + grpc_call_credentials* call_credentials); + +/** Server certificate config object holds the server's public certificates and + associated private keys, as well as any CA certificates needed for client + certificate validation (if applicable). Create using + grpc_ssl_server_certificate_config_create(). */ +typedef struct grpc_ssl_server_certificate_config + grpc_ssl_server_certificate_config; + +/** Object that holds a private key / certificate chain pair in PEM format. */ +typedef struct { + /** private_key is the NULL-terminated string containing the PEM encoding of + the client's private key. */ + const char* private_key; + + /** cert_chain is the NULL-terminated string containing the PEM encoding of + the client's certificate chain. */ + const char* cert_chain; +} grpc_ssl_pem_key_cert_pair; + +/** Creates a grpc_ssl_server_certificate_config object. + - pem_roots_cert is the NULL-terminated string containing the PEM encoding of + the client root certificates. This parameter may be NULL if the server does + not want the client to be authenticated with SSL. + - pem_key_cert_pairs is an array private key / certificate chains of the + server. This parameter cannot be NULL. + - num_key_cert_pairs indicates the number of items in the private_key_files + and cert_chain_files parameters. It must be at least 1. + - It is the caller's responsibility to free this object via + grpc_ssl_server_certificate_config_destroy(). */ +GRPCAPI grpc_ssl_server_certificate_config* +grpc_ssl_server_certificate_config_create( + const char* pem_root_certs, + const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs); + +/** Destroys a grpc_ssl_server_certificate_config object. */ +GRPCAPI void grpc_ssl_server_certificate_config_destroy( + grpc_ssl_server_certificate_config* config); + +/** Callback to retrieve updated SSL server certificates, private keys, and + trusted CAs (for client authentication). + - user_data parameter, if not NULL, contains opaque data to be used by the + callback. + - Use grpc_ssl_server_certificate_config_create to create the config. + - The caller assumes ownership of the config. */ +typedef grpc_ssl_certificate_config_reload_status ( + *grpc_ssl_server_certificate_config_callback)( + void* user_data, grpc_ssl_server_certificate_config** config); + +/** Deprecated in favor of grpc_ssl_verify_peer_options. It will be removed + after all of its call sites are migrated to grpc_ssl_verify_peer_options. + Object that holds additional peer-verification options on a secure + channel. */ +typedef struct { + /** If non-NULL this callback will be invoked with the expected + target_name, the peer's certificate (in PEM format), and whatever + userdata pointer is set below. If a non-zero value is returned by this + callback then it is treated as a verification failure. Invocation of + the callback is blocking, so any implementation should be light-weight. + */ + int (*verify_peer_callback)(const char* target_name, const char* peer_pem, + void* userdata); + /** Arbitrary userdata that will be passed as the last argument to + verify_peer_callback. */ + void* verify_peer_callback_userdata; + /** A destruct callback that will be invoked when the channel is being + cleaned up. The userdata argument will be passed to it. The intent is + to perform any cleanup associated with that userdata. */ + void (*verify_peer_destruct)(void* userdata); +} verify_peer_options; + +/** Object that holds additional peer-verification options on a secure + channel. */ +typedef struct { + /** If non-NULL this callback will be invoked with the expected + target_name, the peer's certificate (in PEM format), and whatever + userdata pointer is set below. If a non-zero value is returned by this + callback then it is treated as a verification failure. Invocation of + the callback is blocking, so any implementation should be light-weight. + */ + int (*verify_peer_callback)(const char* target_name, const char* peer_pem, + void* userdata); + /** Arbitrary userdata that will be passed as the last argument to + verify_peer_callback. */ + void* verify_peer_callback_userdata; + /** A destruct callback that will be invoked when the channel is being + cleaned up. The userdata argument will be passed to it. The intent is + to perform any cleanup associated with that userdata. */ + void (*verify_peer_destruct)(void* userdata); +} grpc_ssl_verify_peer_options; + +/** Deprecated in favor of grpc_ssl_server_credentials_create_ex. It will be + removed after all of its call sites are migrated to + grpc_ssl_server_credentials_create_ex. Creates an SSL credentials object. + The security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. + - pem_root_certs is the NULL-terminated string containing the PEM encoding + of the server root certificates. If this parameter is NULL, the + implementation will first try to dereference the file pointed by the + GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable, and if that fails, + try to get the roots set by grpc_override_ssl_default_roots. Eventually, + if all these fail, it will try to get the roots from a well-known place on + disk (in the grpc install directory). + + gRPC has implemented root cache if the underlying OpenSSL library supports + it. The gRPC root certificates cache is only applicable on the default + root certificates, which is used when this parameter is nullptr. If user + provides their own pem_root_certs, when creating an SSL credential object, + gRPC would not be able to cache it, and each subchannel will generate a + copy of the root store. So it is recommended to avoid providing large room + pem with pem_root_certs parameter to avoid excessive memory consumption, + particularly on mobile platforms such as iOS. + - pem_key_cert_pair is a pointer on the object containing client's private + key and certificate chain. This parameter can be NULL if the client does + not have such a key/cert pair. + - verify_options is an optional verify_peer_options object which holds + additional options controlling how peer certificates are verified. For + example, you can supply a callback which receives the peer's certificate + with which you can do additional verification. Can be NULL, in which + case verification will retain default behavior. Any settings in + verify_options are copied during this call, so the verify_options + object can be released afterwards. */ +GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, + const verify_peer_options* verify_options, void* reserved); + +/* Creates an SSL credentials object. + The security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. + - pem_root_certs is the NULL-terminated string containing the PEM encoding + of the server root certificates. If this parameter is NULL, the + implementation will first try to dereference the file pointed by the + GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable, and if that fails, + try to get the roots set by grpc_override_ssl_default_roots. Eventually, + if all these fail, it will try to get the roots from a well-known place on + disk (in the grpc install directory). + + gRPC has implemented root cache if the underlying OpenSSL library supports + it. The gRPC root certificates cache is only applicable on the default + root certificates, which is used when this parameter is nullptr. If user + provides their own pem_root_certs, when creating an SSL credential object, + gRPC would not be able to cache it, and each subchannel will generate a + copy of the root store. So it is recommended to avoid providing large room + pem with pem_root_certs parameter to avoid excessive memory consumption, + particularly on mobile platforms such as iOS. + - pem_key_cert_pair is a pointer on the object containing client's private + key and certificate chain. This parameter can be NULL if the client does + not have such a key/cert pair. + - verify_options is an optional verify_peer_options object which holds + additional options controlling how peer certificates are verified. For + example, you can supply a callback which receives the peer's certificate + with which you can do additional verification. Can be NULL, in which + case verification will retain default behavior. Any settings in + verify_options are copied during this call, so the verify_options + object can be released afterwards. */ +GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create_ex( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, + const grpc_ssl_verify_peer_options* verify_options, void* reserved); + +/** --- server credentials --- */ + +/** Deprecated in favor of grpc_ssl_server_credentials_create_ex. + Creates an SSL server_credentials object. + - pem_roots_cert is the NULL-terminated string containing the PEM encoding of + the client root certificates. This parameter may be NULL if the server does + not want the client to be authenticated with SSL. + - pem_key_cert_pairs is an array private key / certificate chains of the + server. This parameter cannot be NULL. + - num_key_cert_pairs indicates the number of items in the private_key_files + and cert_chain_files parameters. It should be at least 1. + - force_client_auth, if set to non-zero will force the client to authenticate + with an SSL cert. Note that this option is ignored if pem_root_certs is + NULL. */ +GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, int force_client_auth, void* reserved); + +/** Deprecated in favor of grpc_ssl_server_credentials_create_with_options. + Same as grpc_ssl_server_credentials_create method except uses + grpc_ssl_client_certificate_request_type enum to support more ways to + authenticate client certificates.*/ +GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create_ex( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, + grpc_ssl_client_certificate_request_type client_certificate_request, + void* reserved); + +typedef struct grpc_ssl_server_credentials_options + grpc_ssl_server_credentials_options; + +/** Creates an options object using a certificate config. Use this method when + the certificates and keys of the SSL server will not change during the + server's lifetime. + - Takes ownership of the certificate_config parameter. */ +GRPCAPI grpc_ssl_server_credentials_options* +grpc_ssl_server_credentials_create_options_using_config( + grpc_ssl_client_certificate_request_type client_certificate_request, + grpc_ssl_server_certificate_config* certificate_config); + +/** Creates an options object using a certificate config fetcher. Use this + method to reload the certificates and keys of the SSL server without + interrupting the operation of the server. Initial certificate config will be + fetched during server initialization. + - user_data parameter, if not NULL, contains opaque data which will be passed + to the fetcher (see definition of + grpc_ssl_server_certificate_config_callback). */ +GRPCAPI grpc_ssl_server_credentials_options* +grpc_ssl_server_credentials_create_options_using_config_fetcher( + grpc_ssl_client_certificate_request_type client_certificate_request, + grpc_ssl_server_certificate_config_callback cb, void* user_data); + +/** Destroys a grpc_ssl_server_credentials_options object. */ +GRPCAPI void grpc_ssl_server_credentials_options_destroy( + grpc_ssl_server_credentials_options* options); + +/** Creates an SSL server_credentials object using the provided options struct. + - Takes ownership of the options parameter. */ +GRPCAPI grpc_server_credentials* +grpc_ssl_server_credentials_create_with_options( + grpc_ssl_server_credentials_options* options); + +/** --- Auth Metadata Processing --- */ + +/** Callback function that is called when the metadata processing is done. + - Consumed metadata will be removed from the set of metadata available on the + call. consumed_md may be NULL if no metadata has been consumed. + - Response metadata will be set on the response. response_md may be NULL. + - status is GRPC_STATUS_OK for success or a specific status for an error. + Common error status for auth metadata processing is either + GRPC_STATUS_UNAUTHENTICATED in case of an authentication failure or + GRPC_STATUS PERMISSION_DENIED in case of an authorization failure. + - error_details gives details about the error. May be NULL. */ +typedef void (*grpc_process_auth_metadata_done_cb)( + void* user_data, const grpc_metadata* consumed_md, size_t num_consumed_md, + const grpc_metadata* response_md, size_t num_response_md, + grpc_status_code status, const char* error_details); + +/** Pluggable server-side metadata processor object. */ +typedef struct { + /** The context object is read/write: it contains the properties of the + channel peer and it is the job of the process function to augment it with + properties derived from the passed-in metadata. + The lifetime of these objects is guaranteed until cb is invoked. */ + void (*process)(void* state, grpc_auth_context* context, + const grpc_metadata* md, size_t num_md, + grpc_process_auth_metadata_done_cb cb, void* user_data); + void (*destroy)(void* state); + void* state; +} grpc_auth_metadata_processor; + +GRPCAPI void grpc_server_credentials_set_auth_metadata_processor( + grpc_server_credentials* creds, grpc_auth_metadata_processor processor); + +/** --- composite credentials --- */ + +/** Creates a composite call credentials object. */ +GRPCAPI grpc_call_credentials* grpc_composite_call_credentials_create( + grpc_call_credentials* creds1, grpc_call_credentials* creds2, + void* reserved); + +/** Creates a compute engine credentials object for connecting to Google. + WARNING: Do NOT use this credentials to connect to a non-google service as + this could result in an oauth2 token leak. */ +GRPCAPI grpc_call_credentials* grpc_google_compute_engine_credentials_create( + void* reserved); + +/** Creates a composite channel credentials object. The security level of + * resulting connection is determined by channel_creds. */ +GRPCAPI grpc_channel_credentials* grpc_composite_channel_credentials_create( + grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds, + void* reserved); + +/** --- ALTS channel/server credentials --- **/ + +/** + * Main interface for ALTS credentials options. The options will contain + * information that will be passed from grpc to TSI layer such as RPC protocol + * versions. ALTS client (channel) and server credentials will have their own + * implementation of this interface. The APIs listed in this header are + * thread-compatible. It is used for experimental purpose for now and subject + * to change. + */ +typedef struct grpc_alts_credentials_options grpc_alts_credentials_options; + +/** + * This method creates a grpc ALTS credentials client options instance. + * It is used for experimental purpose for now and subject to change. + */ +GRPCAPI grpc_alts_credentials_options* +grpc_alts_credentials_client_options_create(void); + +/** + * This method creates a grpc ALTS credentials server options instance. + * It is used for experimental purpose for now and subject to change. + */ +GRPCAPI grpc_alts_credentials_options* +grpc_alts_credentials_server_options_create(void); + +/** + * This method adds a target service account to grpc client's ALTS credentials + * options instance. It is used for experimental purpose for now and subject + * to change. + * + * - options: grpc ALTS credentials options instance. + * - service_account: service account of target endpoint. + */ +GRPCAPI void grpc_alts_credentials_client_options_add_target_service_account( + grpc_alts_credentials_options* options, const char* service_account); + +/** + * This method destroys a grpc_alts_credentials_options instance by + * de-allocating all of its occupied memory. It is used for experimental purpose + * for now and subject to change. + * + * - options: a grpc_alts_credentials_options instance that needs to be + * destroyed. + */ +GRPCAPI void grpc_alts_credentials_options_destroy( + grpc_alts_credentials_options* options); + +/** + * This method creates an ALTS channel credential object. The security + * level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. + * It is used for experimental purpose for now and subject to change. + * + * - options: grpc ALTS credentials options instance for client. + * + * It returns the created ALTS channel credential object. + */ +GRPCAPI grpc_channel_credentials* grpc_alts_credentials_create( + const grpc_alts_credentials_options* options); + +/** + * This method creates an ALTS server credential object. It is used for + * experimental purpose for now and subject to change. + * + * - options: grpc ALTS credentials options instance for server. + * + * It returns the created ALTS server credential object. + */ +GRPCAPI grpc_server_credentials* grpc_alts_server_credentials_create( + const grpc_alts_credentials_options* options); + +/** + * EXPERIMENTAL API - Subject to change + * + * A struct that can be specified by callers to configure underlying TLS + * behaviors. + */ +typedef struct grpc_tls_credentials_options grpc_tls_credentials_options; + +/** --- TLS channel/server credentials --- + * It is used for experimental purpose for now and subject to change. */ + +/** + * EXPERIMENTAL API - Subject to change + * + * A struct provides ways to gain credential data that will be used in the TLS + * handshake. + */ +typedef struct grpc_tls_certificate_provider grpc_tls_certificate_provider; + +/** + * EXPERIMENTAL API - Subject to change + * + * A struct that stores the credential data presented to the peer in handshake + * to show local identity. + */ +typedef struct grpc_tls_identity_pairs grpc_tls_identity_pairs; + +/** + * EXPERIMENTAL API - Subject to change + * + * Creates a grpc_tls_identity_pairs that stores a list of identity credential + * data, including identity private key and identity certificate chain. + */ +GRPCAPI grpc_tls_identity_pairs* grpc_tls_identity_pairs_create(); + +/** + * EXPERIMENTAL API - Subject to change + * + * Adds a identity private key and a identity certificate chain to + * grpc_tls_identity_pairs. This function will make an internal copy of + * |private_key| and |cert_chain|. + */ +GRPCAPI void grpc_tls_identity_pairs_add_pair(grpc_tls_identity_pairs* pairs, + const char* private_key, + const char* cert_chain); + +/** + * EXPERIMENTAL API - Subject to change + * + * Destroys a grpc_tls_identity_pairs object. If this object is passed to a + * provider initiation function, the ownership is transferred so this function + * doesn't need to be called. Otherwise the creator of the + * grpc_tls_identity_pairs object is responsible for its destruction. + */ +GRPCAPI void grpc_tls_identity_pairs_destroy(grpc_tls_identity_pairs* pairs); + +/** + * EXPERIMENTAL API - Subject to change + * + * Creates a grpc_tls_certificate_provider that will load credential data from + * static string during initialization. This provider will always return the + * same cert data for all cert names. + * root_certificate and pem_key_cert_pairs can be nullptr, indicating the + * corresponding credential data is not needed. + * This function will make a copy of |root_certificate|. + * The ownership of |pem_key_cert_pairs| is transferred. + */ +GRPCAPI grpc_tls_certificate_provider* +grpc_tls_certificate_provider_static_data_create( + const char* root_certificate, grpc_tls_identity_pairs* pem_key_cert_pairs); + +/** + * EXPERIMENTAL API - Subject to change + * + * Creates a grpc_tls_certificate_provider that will watch the credential + * changes on the file system. This provider will always return the up-to-date + * cert data for all the cert names callers set through + * |grpc_tls_credentials_options|. Note that this API only supports one key-cert + * file and hence one set of identity key-cert pair, so SNI(Server Name + * Indication) is not supported. + * - private_key_path is the file path of the private key. This must be set if + * |identity_certificate_path| is set. Otherwise, it could be null if no + * identity credentials are needed. + * - identity_certificate_path is the file path of the identity certificate + * chain. This must be set if |private_key_path| is set. Otherwise, it could + * be null if no identity credentials are needed. + * - root_cert_path is the file path to the root certificate bundle. This + * may be null if no root certs are needed. + * - refresh_interval_sec is the refreshing interval that we will check the + * files for updates. + * It does not take ownership of parameters. + */ +GRPCAPI grpc_tls_certificate_provider* +grpc_tls_certificate_provider_file_watcher_create( + const char* private_key_path, const char* identity_certificate_path, + const char* root_cert_path, unsigned int refresh_interval_sec); + +/** + * EXPERIMENTAL API - Subject to change + * + * Releases a grpc_tls_certificate_provider object. The creator of the + * grpc_tls_certificate_provider object is responsible for its release. + */ +GRPCAPI void grpc_tls_certificate_provider_release( + grpc_tls_certificate_provider* provider); + +/** + * EXPERIMENTAL API - Subject to change + * + * The read-only request information exposed in a verification call. + * Callers should not directly manage the ownership of it. We will make sure it + * is always available inside verify() or cancel() call, and will destroy the + * object at the end of custom verification. + */ +typedef struct grpc_tls_custom_verification_check_request { + /* The target name of the server when the client initiates the connection. */ + /* This field will be nullptr if on the server side. */ + const char* target_name; + /* The information contained in the certificate chain sent from the peer. */ + struct peer_info { + /* The Common Name field on the peer leaf certificate. */ + const char* common_name; + /* The list of Subject Alternative Names on the peer leaf certificate. */ + struct san_names { + char** uri_names; + size_t uri_names_size; + char** dns_names; + size_t dns_names_size; + char** email_names; + size_t email_names_size; + char** ip_names; + size_t ip_names_size; + } san_names; + /* The raw peer leaf certificate. */ + const char* peer_cert; + /* The raw peer certificate chain. Note that it is not always guaranteed to + * get the peer full chain. For more, please refer to + * GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME defined in file + * grpc_security_constants.h. + * TODO(ZhenLian): Consider fixing this in the future. */ + const char* peer_cert_full_chain; + /* The verified root cert subject. + * This value will only be filled if the cryptographic peer certificate + * verification was successful */ + const char* verified_root_cert_subject; + } peer_info; +} grpc_tls_custom_verification_check_request; + +/** + * EXPERIMENTAL API - Subject to change + * + * A callback function provided by gRPC as a parameter of the |verify| function + * in grpc_tls_certificate_verifier_external. If |verify| is expected to be run + * asynchronously, the implementer of |verify| will need to invoke this callback + * with |callback_arg| and proper verification status at the end to bring the + * control back to gRPC C core. + */ +typedef void (*grpc_tls_on_custom_verification_check_done_cb)( + grpc_tls_custom_verification_check_request* request, void* callback_arg, + grpc_status_code status, const char* error_details); + +/** + * EXPERIMENTAL API - Subject to change + * + * The internal verifier type that will be used inside core. + */ +typedef struct grpc_tls_certificate_verifier grpc_tls_certificate_verifier; + +/** + * EXPERIMENTAL API - Subject to change + * + * A struct containing all the necessary functions a custom external verifier + * needs to implement to be able to be converted to an internal verifier. + */ +typedef struct grpc_tls_certificate_verifier_external { + void* user_data; + /** + * A function pointer containing the verification logic that will be + * performed after the TLS handshake is done. It could be processed + * synchronously or asynchronously. + * - If expected to be processed synchronously, the implementer should + * populate the verification result through |sync_status| and + * |sync_error_details|, and then return true. + * - If expected to be processed asynchronously, the implementer should return + * false immediately, and then in the asynchronous thread invoke |callback| + * with the verification result. The implementer MUST NOT invoke the async + * |callback| in the same thread before |verify| returns, otherwise it can + * lead to deadlocks. + * + * user_data: any argument that is passed in the user_data of + * grpc_tls_certificate_verifier_external during construction time + * can be retrieved later here. + * request: request information exposed to the function implementer. + * callback: the callback that the function implementer needs to invoke, if + * return a non-zero value. It is usually invoked when the + * asynchronous verification is done, and serves to bring the + * control back to gRPC. + * callback_arg: A pointer to the internal ExternalVerifier instance. This is + * mainly used as an argument in |callback|, if want to invoke + * |callback| in async mode. + * sync_status: indicates if a connection should be allowed. This should only + * be used if the verification check is done synchronously. + * sync_error_details: the error generated while verifying a connection. This + * should only be used if the verification check is done + * synchronously. the implementation must allocate the + * error string via gpr_malloc() or gpr_strdup(). + * return: return 0 if |verify| is expected to be executed asynchronously, + * otherwise return a non-zero value. + */ + int (*verify)(void* user_data, + grpc_tls_custom_verification_check_request* request, + grpc_tls_on_custom_verification_check_done_cb callback, + void* callback_arg, grpc_status_code* sync_status, + char** sync_error_details); + /** + * A function pointer that cleans up the caller-specified resources when the + * verifier is still running but the whole connection got cancelled. This + * could happen when the verifier is doing some async operations, and the + * whole handshaker object got destroyed because of connection time limit is + * reached, or any other reasons. In such cases, function implementers might + * want to be notified, and properly clean up some resources. + * + * user_data: any argument that is passed in the user_data of + * grpc_tls_certificate_verifier_external during construction time + * can be retrieved later here. + * request: request information exposed to the function implementer. It will + * be the same request object that was passed to verify(), and it + * tells the cancel() which request to cancel. + */ + void (*cancel)(void* user_data, + grpc_tls_custom_verification_check_request* request); + /** + * A function pointer that does some additional destruction work when the + * verifier is destroyed. This is used when the caller wants to associate some + * objects to the lifetime of external_verifier, and destroy them when + * external_verifier got destructed. For example, in C++, the class containing + * user-specified callback functions should not be destroyed before + * external_verifier, since external_verifier will invoke them while being + * used. + * Note that the caller MUST delete the grpc_tls_certificate_verifier_external + * object itself in this function, otherwise it will cause memory leaks. That + * also means the user_data has to carries at least a self pointer, for the + * callers to later delete it in destruct(). + * + * user_data: any argument that is passed in the user_data of + * grpc_tls_certificate_verifier_external during construction time + * can be retrieved later here. + */ + void (*destruct)(void* user_data); +} grpc_tls_certificate_verifier_external; + +/** + * EXPERIMENTAL API - Subject to change + * + * Converts an external verifier to an internal verifier. + * Note that we will not take the ownership of the external_verifier. Callers + * will need to delete external_verifier in its own destruct function. + */ +grpc_tls_certificate_verifier* grpc_tls_certificate_verifier_external_create( + grpc_tls_certificate_verifier_external* external_verifier); + +/** + * EXPERIMENTAL API - Subject to change + * + * Factory function for an internal verifier that won't perform any + * post-handshake verification. Note: using this solely without any other + * authentication mechanisms on the peer identity will leave your applications + * to the MITM(Man-In-The-Middle) attacks. Users should avoid doing so in + * production environments. + */ +grpc_tls_certificate_verifier* grpc_tls_certificate_verifier_no_op_create(); + +/** + * EXPERIMENTAL API - Subject to change + * + * Factory function for an internal verifier that will do the default hostname + * check. + */ +grpc_tls_certificate_verifier* grpc_tls_certificate_verifier_host_name_create(); + +/** + * EXPERIMENTAL API - Subject to change + * + * Releases a grpc_tls_certificate_verifier object. The creator of the + * grpc_tls_certificate_verifier object is responsible for its release. + */ +void grpc_tls_certificate_verifier_release( + grpc_tls_certificate_verifier* verifier); + +/** + * EXPERIMENTAL API - Subject to change + * + * Performs the verification logic of an internal verifier. + * This is typically used when composing the internal verifiers as part of the + * custom verification. + * If |grpc_tls_certificate_verifier_verify| returns true, inspect the + * verification result through request->status and request->error_details. + * Otherwise, inspect through the parameter of |callback|. + */ +int grpc_tls_certificate_verifier_verify( + grpc_tls_certificate_verifier* verifier, + grpc_tls_custom_verification_check_request* request, + grpc_tls_on_custom_verification_check_done_cb callback, void* callback_arg, + grpc_status_code* sync_status, char** sync_error_details); + +/** + * EXPERIMENTAL API - Subject to change + * + * Performs the cancellation logic of an internal verifier. + * This is typically used when composing the internal verifiers as part of the + * custom verification. + */ +void grpc_tls_certificate_verifier_cancel( + grpc_tls_certificate_verifier* verifier, + grpc_tls_custom_verification_check_request* request); + +/** + * EXPERIMENTAL API - Subject to change + * + * Creates an grpc_tls_credentials_options. + */ +GRPCAPI grpc_tls_credentials_options* grpc_tls_credentials_options_create(void); + +/** + * EXPERIMENTAL API - Subject to change + * + * Creates a TLS channel credential object based on the + * grpc_tls_credentials_options specified by callers. The + * grpc_channel_credentials will take the ownership of the |options|. The + * security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. + */ +grpc_channel_credentials* grpc_tls_credentials_create( + grpc_tls_credentials_options* options); + +/** + * EXPERIMENTAL API - Subject to change + * + * Creates a TLS server credential object based on the + * grpc_tls_credentials_options specified by callers. The + * grpc_server_credentials will take the ownership of the |options|. + */ +grpc_server_credentials* grpc_tls_server_credentials_create( + grpc_tls_credentials_options* options); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the minimum TLS version that will be negotiated during the TLS + * handshake. If not set, the underlying SSL library will set it to TLS v1.2. + */ +GRPCAPI void grpc_tls_credentials_options_set_min_tls_version( + grpc_tls_credentials_options* options, grpc_tls_version min_tls_version); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the maximum TLS version that will be negotiated during the TLS + * handshake. If not set, the underlying SSL library will set it to TLS v1.3. + */ +GRPCAPI void grpc_tls_credentials_options_set_max_tls_version( + grpc_tls_credentials_options* options, grpc_tls_version max_tls_version); + +/** + * EXPERIMENTAL API - Subject to change + * + * Copies a grpc_tls_credentials_options. + */ +GRPCAPI grpc_tls_credentials_options* grpc_tls_credentials_options_copy( + grpc_tls_credentials_options* options); + +/** + * EXPERIMENTAL API - Subject to change + * + * Destroys a grpc_tls_credentials_options. + */ +GRPCAPI void grpc_tls_credentials_options_destroy( + grpc_tls_credentials_options* options); + +/** + * EXPERIMENTAL API - Subject to change + * + * A struct provides ways to gain credential data that will be used in the TLS + * handshake. + */ +typedef struct grpc_tls_certificate_provider grpc_tls_certificate_provider; + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the credential provider in the options. + * The |options| will implicitly take a new ref to the |provider|. + */ +GRPCAPI void grpc_tls_credentials_options_set_certificate_provider( + grpc_tls_credentials_options* options, + grpc_tls_certificate_provider* provider); + +/** + * EXPERIMENTAL API - Subject to change + * + * If set, gRPC stack will keep watching the root certificates with + * name |root_cert_name|. + * If this is not set on the client side, we will use the root certificates + * stored in the default system location, since client side must provide root + * certificates in TLS. + * If this is not set on the server side, we will not watch any root certificate + * updates, and assume no root certificates needed for the server(single-side + * TLS). Default root certs on the server side is not supported. + */ +GRPCAPI void grpc_tls_credentials_options_watch_root_certs( + grpc_tls_credentials_options* options); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the name of the root certificates being watched. + * If not set, We will use a default empty string as the root certificate name. + */ +GRPCAPI void grpc_tls_credentials_options_set_root_cert_name( + grpc_tls_credentials_options* options, const char* root_cert_name); + +/** + * EXPERIMENTAL API - Subject to change + * + * If set, gRPC stack will keep watching the identity key-cert pairs + * with name |identity_cert_name|. + * This is required on the server side, and optional on the client side. + */ +GRPCAPI void grpc_tls_credentials_options_watch_identity_key_cert_pairs( + grpc_tls_credentials_options* options); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the name of the identity certificates being watched. + * If not set, We will use a default empty string as the identity certificate + * name. + */ +GRPCAPI void grpc_tls_credentials_options_set_identity_cert_name( + grpc_tls_credentials_options* options, const char* identity_cert_name); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the options of whether to request and/or verify client certs. This shall + * only be called on the server side. + */ +GRPCAPI void grpc_tls_credentials_options_set_cert_request_type( + grpc_tls_credentials_options* options, + grpc_ssl_client_certificate_request_type type); + +/** Deprecated in favor of grpc_tls_credentials_options_set_crl_provider. The + * crl provider interface provides a significantly more flexible approach to + * using CRLs. See gRFC A69 for details. + * EXPERIMENTAL API - Subject to change + * + * If set, gRPC will read all hashed x.509 CRL files in the directory and + * enforce the CRL files on all TLS handshakes. Only supported for OpenSSL + * version > 1.1. + * It is used for experimental purpose for now and subject to change. + */ +GRPCAPI void grpc_tls_credentials_options_set_crl_directory( + grpc_tls_credentials_options* options, const char* crl_directory); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the options of whether to verify server certs on the client side. + * Passing in a non-zero value indicates verifying the certs. + */ +GRPCAPI void grpc_tls_credentials_options_set_verify_server_cert( + grpc_tls_credentials_options* options, int verify_server_cert); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets whether or not a TLS server should send a list of CA names in the + * ServerHello. This list of CA names is read from the server's trust bundle, so + * that the client can use this list as a hint to know which certificate it + * should send to the server. + * + * WARNING: This API is extremely dangerous and should not be used. If the + * server's trust bundle is too large, then the TLS server will be unable to + * form a ServerHello, and hence will be unusable. The definition of "too large" + * depends on the underlying SSL library being used and on the size of the CN + * fields of the certificates in the trust bundle. + */ +GRPCAPI void grpc_tls_credentials_options_set_send_client_ca_list( + grpc_tls_credentials_options* options, bool send_client_ca_list); + +/** --- SSL Session Cache. --- + + A SSL session cache object represents a way to cache client sessions + between connections. Only ticket-based resumption is supported. */ + +typedef struct grpc_ssl_session_cache grpc_ssl_session_cache; + +/** Create LRU cache for client-side SSL sessions with the given capacity. + If capacity is < 1, a default capacity is used instead. */ +GRPCAPI grpc_ssl_session_cache* grpc_ssl_session_cache_create_lru( + size_t capacity); + +/** Destroy SSL session cache. */ +GRPCAPI void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache); + +/** Create a channel arg with the given cache object. */ +GRPCAPI grpc_arg +grpc_ssl_session_cache_create_channel_arg(grpc_ssl_session_cache* cache); + +/** Callback for getting the SSL roots override from the application. + In case of success, *pem_roots_certs must be set to a NULL terminated string + containing the list of PEM encoded root certificates. The ownership is passed + to the core and freed (laster by the core) with gpr_free. + If this function fails and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment is + set to a valid path, it will override the roots specified this func */ +typedef grpc_ssl_roots_override_result (*grpc_ssl_roots_override_callback)( + char** pem_root_certs); + +/** Setup a callback to override the default TLS/SSL roots. + This function is not thread-safe and must be called at initialization time + before any ssl credentials are created to have the desired side effect. + If GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment is set to a valid path, the + callback will not be called. */ +GRPCAPI void grpc_set_ssl_roots_override_callback( + grpc_ssl_roots_override_callback cb); + +GRPCAPI gpr_timespec grpc_max_auth_token_lifetime(void); + +/** --- insecure credentials --- */ + +/** + * EXPERIMENTAL API - Subject to change + * + * This method creates an insecure channel credentials object. + */ +GRPCAPI grpc_channel_credentials* grpc_insecure_credentials_create(); + +/** + * EXPERIMENTAL API - Subject to change + * + * This method creates an insecure server credentials object. + */ +GRPCAPI grpc_server_credentials* grpc_insecure_server_credentials_create(); + +/** + * EXPERIMENTAL API - Subject to change + * + * This method creates an xDS channel credentials object. + * + * Creating a channel with credentials of this type indicates that the channel + * should get credentials configuration from the xDS control plane. + * + * \a fallback_credentials are used if the channel target does not have the + * 'xds:///' scheme or if the xDS control plane does not provide information on + * how to fetch credentials dynamically. Does NOT take ownership of the \a + * fallback_credentials. (Internally takes a ref to the object.) + */ +GRPCAPI grpc_channel_credentials* grpc_xds_credentials_create( + grpc_channel_credentials* fallback_credentials); + +/** + * EXPERIMENTAL API - Subject to change + * + * This method creates an xDS server credentials object. + * + * \a fallback_credentials are used if the xDS control plane does not provide + * information on how to fetch credentials dynamically. + * + * Does NOT take ownership of the \a fallback_credentials. (Internally takes + * a ref to the object.) + */ +GRPCAPI grpc_server_credentials* grpc_xds_server_credentials_create( + grpc_server_credentials* fallback_credentials); + +/** --- Local channel/server credentials --- **/ + +/** + * This method creates a local channel credential object. The security level + * of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY for UDS and + * GRPC_SECURITY_NONE for LOCAL_TCP. It is used for experimental purpose + * for now and subject to change. + * + * - type: local connection type + * + * It returns the created local channel credential object. + */ +GRPCAPI grpc_channel_credentials* grpc_local_credentials_create( + grpc_local_connect_type type); + +/** + * This method creates a local server credential object. It is used for + * experimental purpose for now and subject to change. + * + * - type: local connection type + * + * It returns the created local server credential object. + */ +GRPCAPI grpc_server_credentials* grpc_local_server_credentials_create( + grpc_local_connect_type type); + +/** + * EXPERIMENTAL API - Subject to change + * + * The internal verifier type that will be used inside core. + */ +typedef struct grpc_tls_certificate_verifier grpc_tls_certificate_verifier; + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the verifier in options. The |options| will implicitly take a new ref to + * the |verifier|. If not set on the client side, we will verify server's + * certificates, and check the default hostname. If not set on the server side, + * we will verify client's certificates. + */ +void grpc_tls_credentials_options_set_certificate_verifier( + grpc_tls_credentials_options* options, + grpc_tls_certificate_verifier* verifier); + +/** + * EXPERIMENTAL API - Subject to change + * + * Sets the options of whether to check the hostname of the peer on a per-call + * basis. This is usually used in a combination with virtual hosting at the + * client side, where each individual call on a channel can have a different + * host associated with it. + * This check is intended to verify that the host specified for the individual + * call is covered by the cert that the peer presented. + * The default is a non-zero value, which indicates performing such checks. + */ +GRPCAPI void grpc_tls_credentials_options_set_check_call_host( + grpc_tls_credentials_options* options, int check_call_host); + +/** --- TLS session key logging. --- + * Experimental API to control tls session key logging. Tls session key logging + * is expected to be used only for debugging purposes and never in production. + * Tls session key logging is only enabled when: + * At least one grpc_tls_credentials_options object is assigned a tls session + * key logging file path using the API specified below. + */ + +/** + * EXPERIMENTAL API - Subject to change. + * Configures a grpc_tls_credentials_options object with tls session key + * logging capability. TLS channels using these credentials have tls session + * key logging enabled. + * - options is the grpc_tls_credentials_options object + * - path is a string pointing to the location where TLS session keys would be + * stored. + */ +GRPCAPI void grpc_tls_credentials_options_set_tls_session_key_log_file_path( + grpc_tls_credentials_options* options, const char* path); + +#ifdef __cplusplus +} +#endif + +#endif /* GRPC_CREDENTIALS_H */ diff --git a/include/grpc/grpc.h b/include/grpc/grpc.h index 20527730358..d293907eac0 100644 --- a/include/grpc/grpc.h +++ b/include/grpc/grpc.h @@ -361,6 +361,13 @@ GRPCAPI void grpc_call_ref(grpc_call* call); THREAD SAFETY: grpc_call_unref is thread-compatible */ GRPCAPI void grpc_call_unref(grpc_call* call); +typedef struct grpc_call_credentials grpc_call_credentials; + +/** Sets a credentials to a call. Can only be called on the client side before + grpc_call_start_batch. */ +GRPCAPI grpc_call_error grpc_call_set_credentials(grpc_call* call, + grpc_call_credentials* creds); + /** Request notification of a new call. Once a call is received, a notification tagged with \a tag_new is added to \a cq_for_notification. \a call, \a details and \a request_metadata are diff --git a/include/grpc/grpc_crl_provider.h b/include/grpc/grpc_crl_provider.h index 04e8ffa0901..35d6df6f939 100644 --- a/include/grpc/grpc_crl_provider.h +++ b/include/grpc/grpc_crl_provider.h @@ -25,6 +25,7 @@ #include "absl/status/statusor.h" #include "absl/strings/string_view.h" +#include #include #include diff --git a/include/grpc/grpc_security.h b/include/grpc/grpc_security.h index 5524170a2ac..11e08a6f4a1 100644 --- a/include/grpc/grpc_security.h +++ b/include/grpc/grpc_security.h @@ -101,1157 +101,6 @@ GRPCAPI void grpc_auth_context_add_cstring_property(grpc_auth_context* ctx, GRPCAPI int grpc_auth_context_set_peer_identity_property_name( grpc_auth_context* ctx, const char* name); -/** --- SSL Session Cache. --- - - A SSL session cache object represents a way to cache client sessions - between connections. Only ticket-based resumption is supported. */ - -typedef struct grpc_ssl_session_cache grpc_ssl_session_cache; - -/** Create LRU cache for client-side SSL sessions with the given capacity. - If capacity is < 1, a default capacity is used instead. */ -GRPCAPI grpc_ssl_session_cache* grpc_ssl_session_cache_create_lru( - size_t capacity); - -/** Destroy SSL session cache. */ -GRPCAPI void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache); - -/** Create a channel arg with the given cache object. */ -GRPCAPI grpc_arg -grpc_ssl_session_cache_create_channel_arg(grpc_ssl_session_cache* cache); - -/** --- grpc_call_credentials object. - - A call credentials object represents a way to authenticate on a particular - call. These credentials can be composed with a channel credentials object - so that they are sent with every call on this channel. */ - -typedef struct grpc_call_credentials grpc_call_credentials; - -/** Releases a call credentials object. - The creator of the credentials object is responsible for its release. */ -GRPCAPI void grpc_call_credentials_release(grpc_call_credentials* creds); - -/** Creates default credentials to connect to a google gRPC service. - WARNING: Do NOT use this credentials to connect to a non-google service as - this could result in an oauth2 token leak. The security level of the - resulting connection is GRPC_PRIVACY_AND_INTEGRITY. - - If specified, the supplied call credentials object will be attached to the - returned channel credentials object. The call_credentials object must remain - valid throughout the lifetime of the returned grpc_channel_credentials - object. It is expected that the call credentials object was generated - according to the Application Default Credentials mechanism and asserts the - identity of the default service account of the machine. Supplying any other - sort of call credential will result in undefined behavior, up to and - including the sudden and unexpected failure of RPCs. - - If nullptr is supplied, the returned channel credentials object will use a - call credentials object based on the Application Default Credentials - mechanism. -*/ -GRPCAPI grpc_channel_credentials* grpc_google_default_credentials_create( - grpc_call_credentials* call_credentials); - -/** Callback for getting the SSL roots override from the application. - In case of success, *pem_roots_certs must be set to a NULL terminated string - containing the list of PEM encoded root certificates. The ownership is passed - to the core and freed (laster by the core) with gpr_free. - If this function fails and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment is - set to a valid path, it will override the roots specified this func */ -typedef grpc_ssl_roots_override_result (*grpc_ssl_roots_override_callback)( - char** pem_root_certs); - -/** Setup a callback to override the default TLS/SSL roots. - This function is not thread-safe and must be called at initialization time - before any ssl credentials are created to have the desired side effect. - If GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment is set to a valid path, the - callback will not be called. */ -GRPCAPI void grpc_set_ssl_roots_override_callback( - grpc_ssl_roots_override_callback cb); - -/** Object that holds a private key / certificate chain pair in PEM format. */ -typedef struct { - /** private_key is the NULL-terminated string containing the PEM encoding of - the client's private key. */ - const char* private_key; - - /** cert_chain is the NULL-terminated string containing the PEM encoding of - the client's certificate chain. */ - const char* cert_chain; -} grpc_ssl_pem_key_cert_pair; - -/** Deprecated in favor of grpc_ssl_verify_peer_options. It will be removed - after all of its call sites are migrated to grpc_ssl_verify_peer_options. - Object that holds additional peer-verification options on a secure - channel. */ -typedef struct { - /** If non-NULL this callback will be invoked with the expected - target_name, the peer's certificate (in PEM format), and whatever - userdata pointer is set below. If a non-zero value is returned by this - callback then it is treated as a verification failure. Invocation of - the callback is blocking, so any implementation should be light-weight. - */ - int (*verify_peer_callback)(const char* target_name, const char* peer_pem, - void* userdata); - /** Arbitrary userdata that will be passed as the last argument to - verify_peer_callback. */ - void* verify_peer_callback_userdata; - /** A destruct callback that will be invoked when the channel is being - cleaned up. The userdata argument will be passed to it. The intent is - to perform any cleanup associated with that userdata. */ - void (*verify_peer_destruct)(void* userdata); -} verify_peer_options; - -/** Object that holds additional peer-verification options on a secure - channel. */ -typedef struct { - /** If non-NULL this callback will be invoked with the expected - target_name, the peer's certificate (in PEM format), and whatever - userdata pointer is set below. If a non-zero value is returned by this - callback then it is treated as a verification failure. Invocation of - the callback is blocking, so any implementation should be light-weight. - */ - int (*verify_peer_callback)(const char* target_name, const char* peer_pem, - void* userdata); - /** Arbitrary userdata that will be passed as the last argument to - verify_peer_callback. */ - void* verify_peer_callback_userdata; - /** A destruct callback that will be invoked when the channel is being - cleaned up. The userdata argument will be passed to it. The intent is - to perform any cleanup associated with that userdata. */ - void (*verify_peer_destruct)(void* userdata); -} grpc_ssl_verify_peer_options; - -/** Deprecated in favor of grpc_ssl_server_credentials_create_ex. It will be - removed after all of its call sites are migrated to - grpc_ssl_server_credentials_create_ex. Creates an SSL credentials object. - The security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. - - pem_root_certs is the NULL-terminated string containing the PEM encoding - of the server root certificates. If this parameter is NULL, the - implementation will first try to dereference the file pointed by the - GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable, and if that fails, - try to get the roots set by grpc_override_ssl_default_roots. Eventually, - if all these fail, it will try to get the roots from a well-known place on - disk (in the grpc install directory). - - gRPC has implemented root cache if the underlying OpenSSL library supports - it. The gRPC root certificates cache is only applicable on the default - root certificates, which is used when this parameter is nullptr. If user - provides their own pem_root_certs, when creating an SSL credential object, - gRPC would not be able to cache it, and each subchannel will generate a - copy of the root store. So it is recommended to avoid providing large room - pem with pem_root_certs parameter to avoid excessive memory consumption, - particularly on mobile platforms such as iOS. - - pem_key_cert_pair is a pointer on the object containing client's private - key and certificate chain. This parameter can be NULL if the client does - not have such a key/cert pair. - - verify_options is an optional verify_peer_options object which holds - additional options controlling how peer certificates are verified. For - example, you can supply a callback which receives the peer's certificate - with which you can do additional verification. Can be NULL, in which - case verification will retain default behavior. Any settings in - verify_options are copied during this call, so the verify_options - object can be released afterwards. */ -GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create( - const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, - const verify_peer_options* verify_options, void* reserved); - -/* Creates an SSL credentials object. - The security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. - - pem_root_certs is the NULL-terminated string containing the PEM encoding - of the server root certificates. If this parameter is NULL, the - implementation will first try to dereference the file pointed by the - GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable, and if that fails, - try to get the roots set by grpc_override_ssl_default_roots. Eventually, - if all these fail, it will try to get the roots from a well-known place on - disk (in the grpc install directory). - - gRPC has implemented root cache if the underlying OpenSSL library supports - it. The gRPC root certificates cache is only applicable on the default - root certificates, which is used when this parameter is nullptr. If user - provides their own pem_root_certs, when creating an SSL credential object, - gRPC would not be able to cache it, and each subchannel will generate a - copy of the root store. So it is recommended to avoid providing large room - pem with pem_root_certs parameter to avoid excessive memory consumption, - particularly on mobile platforms such as iOS. - - pem_key_cert_pair is a pointer on the object containing client's private - key and certificate chain. This parameter can be NULL if the client does - not have such a key/cert pair. - - verify_options is an optional verify_peer_options object which holds - additional options controlling how peer certificates are verified. For - example, you can supply a callback which receives the peer's certificate - with which you can do additional verification. Can be NULL, in which - case verification will retain default behavior. Any settings in - verify_options are copied during this call, so the verify_options - object can be released afterwards. */ -GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create_ex( - const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, - const grpc_ssl_verify_peer_options* verify_options, void* reserved); - -/** Creates a composite channel credentials object. The security level of - * resulting connection is determined by channel_creds. */ -GRPCAPI grpc_channel_credentials* grpc_composite_channel_credentials_create( - grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds, - void* reserved); - -/** --- composite credentials. */ - -/** Creates a composite call credentials object. */ -GRPCAPI grpc_call_credentials* grpc_composite_call_credentials_create( - grpc_call_credentials* creds1, grpc_call_credentials* creds2, - void* reserved); - -/** Creates a compute engine credentials object for connecting to Google. - WARNING: Do NOT use this credentials to connect to a non-google service as - this could result in an oauth2 token leak. */ -GRPCAPI grpc_call_credentials* grpc_google_compute_engine_credentials_create( - void* reserved); - -GRPCAPI gpr_timespec grpc_max_auth_token_lifetime(void); - -/** Creates a JWT credentials object. May return NULL if the input is invalid. - - json_key is the JSON key string containing the client's private key. - - token_lifetime is the lifetime of each Json Web Token (JWT) created with - this credentials. It should not exceed grpc_max_auth_token_lifetime or - will be cropped to this value. */ -GRPCAPI grpc_call_credentials* -grpc_service_account_jwt_access_credentials_create(const char* json_key, - gpr_timespec token_lifetime, - void* reserved); - -/** Builds External Account credentials. - - json_string is the JSON string containing the credentials options. - - scopes_string contains the scopes to be binded with the credentials. - This API is used for experimental purposes for now and may change in the - future. */ -GRPCAPI grpc_call_credentials* grpc_external_account_credentials_create( - const char* json_string, const char* scopes_string); - -/** Creates an Oauth2 Refresh Token credentials object for connecting to Google. - May return NULL if the input is invalid. - WARNING: Do NOT use this credentials to connect to a non-google service as - this could result in an oauth2 token leak. - - json_refresh_token is the JSON string containing the refresh token itself - along with a client_id and client_secret. */ -GRPCAPI grpc_call_credentials* grpc_google_refresh_token_credentials_create( - const char* json_refresh_token, void* reserved); - -/** Creates an Oauth2 Access Token credentials with an access token that was - acquired by an out of band mechanism. */ -GRPCAPI grpc_call_credentials* grpc_access_token_credentials_create( - const char* access_token, void* reserved); - -/** Creates an IAM credentials object for connecting to Google. */ -GRPCAPI grpc_call_credentials* grpc_google_iam_credentials_create( - const char* authorization_token, const char* authority_selector, - void* reserved); - -/** Options for creating STS Oauth Token Exchange credentials following the IETF - draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16. - Optional fields may be set to NULL or empty string. It is the responsibility - of the caller to ensure that the subject and actor tokens are refreshed on - disk at the specified paths. This API is used for experimental purposes for - now and may change in the future. */ -typedef struct { - const char* token_exchange_service_uri; /* Required. */ - const char* resource; /* Optional. */ - const char* audience; /* Optional. */ - const char* scope; /* Optional. */ - const char* requested_token_type; /* Optional. */ - const char* subject_token_path; /* Required. */ - const char* subject_token_type; /* Required. */ - const char* actor_token_path; /* Optional. */ - const char* actor_token_type; /* Optional. */ -} grpc_sts_credentials_options; - -/** Creates an STS credentials following the STS Token Exchanged specifed in the - IETF draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16. - This API is used for experimental purposes for now and may change in the - future. */ -GRPCAPI grpc_call_credentials* grpc_sts_credentials_create( - const grpc_sts_credentials_options* options, void* reserved); - -/** Callback function to be called by the metadata credentials plugin - implementation when the metadata is ready. - - user_data is the opaque pointer that was passed in the get_metadata method - of the grpc_metadata_credentials_plugin (see below). - - creds_md is an array of credentials metadata produced by the plugin. It - may be set to NULL in case of an error. - - num_creds_md is the number of items in the creds_md array. - - status must be GRPC_STATUS_OK in case of success or another specific error - code otherwise. - - error_details contains details about the error if any. In case of success - it should be NULL and will be otherwise ignored. */ -typedef void (*grpc_credentials_plugin_metadata_cb)( - void* user_data, const grpc_metadata* creds_md, size_t num_creds_md, - grpc_status_code status, const char* error_details); - -/** Context that can be used by metadata credentials plugin in order to create - auth related metadata. */ -typedef struct { - /** The fully qualifed service url. */ - const char* service_url; - - /** The method name of the RPC being called (not fully qualified). - The fully qualified method name can be built from the service_url: - full_qualified_method_name = ctx->service_url + '/' + ctx->method_name. */ - const char* method_name; - - /** The auth_context of the channel which gives the server's identity. */ - const grpc_auth_context* channel_auth_context; - - /** Reserved for future use. */ - void* reserved; -} grpc_auth_metadata_context; - -/** Performs a deep copy from \a from to \a to. **/ -GRPCAPI void grpc_auth_metadata_context_copy(grpc_auth_metadata_context* from, - grpc_auth_metadata_context* to); - -/** Releases internal resources held by \a context. **/ -GRPCAPI void grpc_auth_metadata_context_reset( - grpc_auth_metadata_context* context); - -/** Maximum number of metadata entries returnable by a credentials plugin via - a synchronous return. */ -#define GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX 4 - -/** grpc_metadata_credentials plugin is an API user provided structure used to - create grpc_credentials objects that can be set on a channel (composed) or - a call. See grpc_credentials_metadata_create_from_plugin below. - The grpc client stack will call the get_metadata method of the plugin for - every call in scope for the credentials created from it. */ -typedef struct { - /** The implementation of this method has to be non-blocking, but can - be performed synchronously or asynchronously. - - If processing occurs synchronously, returns non-zero and populates - creds_md, num_creds_md, status, and error_details. In this case, - the caller takes ownership of the entries in creds_md and of - error_details. Note that if the plugin needs to return more than - GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX entries in creds_md, it must - return asynchronously. - - If processing occurs asynchronously, returns zero and invokes \a cb - when processing is completed. \a user_data will be passed as the - first parameter of the callback. NOTE: \a cb MUST be invoked in a - different thread, not from the thread in which \a get_metadata() is - invoked. - - \a context is the information that can be used by the plugin to create - auth metadata. */ - int (*get_metadata)( - void* state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void* user_data, - grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t* num_creds_md, grpc_status_code* status, - const char** error_details); - - /** Implements debug string of the given plugin. This method returns an - * allocated string that the caller needs to free using gpr_free() */ - char* (*debug_string)(void* state); - - /** Destroys the plugin state. */ - void (*destroy)(void* state); - - /** State that will be set as the first parameter of the methods above. */ - void* state; - - /** Type of credentials that this plugin is implementing. */ - const char* type; -} grpc_metadata_credentials_plugin; - -/** Creates a credentials object from a plugin with a specified minimum security - * level. */ -GRPCAPI grpc_call_credentials* grpc_metadata_credentials_create_from_plugin( - grpc_metadata_credentials_plugin plugin, - grpc_security_level min_security_level, void* reserved); - -/** Server certificate config object holds the server's public certificates and - associated private keys, as well as any CA certificates needed for client - certificate validation (if applicable). Create using - grpc_ssl_server_certificate_config_create(). */ -typedef struct grpc_ssl_server_certificate_config - grpc_ssl_server_certificate_config; - -/** Creates a grpc_ssl_server_certificate_config object. - - pem_roots_cert is the NULL-terminated string containing the PEM encoding of - the client root certificates. This parameter may be NULL if the server does - not want the client to be authenticated with SSL. - - pem_key_cert_pairs is an array private key / certificate chains of the - server. This parameter cannot be NULL. - - num_key_cert_pairs indicates the number of items in the private_key_files - and cert_chain_files parameters. It must be at least 1. - - It is the caller's responsibility to free this object via - grpc_ssl_server_certificate_config_destroy(). */ -GRPCAPI grpc_ssl_server_certificate_config* -grpc_ssl_server_certificate_config_create( - const char* pem_root_certs, - const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, - size_t num_key_cert_pairs); - -/** Destroys a grpc_ssl_server_certificate_config object. */ -GRPCAPI void grpc_ssl_server_certificate_config_destroy( - grpc_ssl_server_certificate_config* config); - -/** Callback to retrieve updated SSL server certificates, private keys, and - trusted CAs (for client authentication). - - user_data parameter, if not NULL, contains opaque data to be used by the - callback. - - Use grpc_ssl_server_certificate_config_create to create the config. - - The caller assumes ownership of the config. */ -typedef grpc_ssl_certificate_config_reload_status ( - *grpc_ssl_server_certificate_config_callback)( - void* user_data, grpc_ssl_server_certificate_config** config); - -/** Deprecated in favor of grpc_ssl_server_credentials_create_ex. - Creates an SSL server_credentials object. - - pem_roots_cert is the NULL-terminated string containing the PEM encoding of - the client root certificates. This parameter may be NULL if the server does - not want the client to be authenticated with SSL. - - pem_key_cert_pairs is an array private key / certificate chains of the - server. This parameter cannot be NULL. - - num_key_cert_pairs indicates the number of items in the private_key_files - and cert_chain_files parameters. It should be at least 1. - - force_client_auth, if set to non-zero will force the client to authenticate - with an SSL cert. Note that this option is ignored if pem_root_certs is - NULL. */ -GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create( - const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, - size_t num_key_cert_pairs, int force_client_auth, void* reserved); - -/** Deprecated in favor of grpc_ssl_server_credentials_create_with_options. - Same as grpc_ssl_server_credentials_create method except uses - grpc_ssl_client_certificate_request_type enum to support more ways to - authenticate client certificates.*/ -GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create_ex( - const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, - size_t num_key_cert_pairs, - grpc_ssl_client_certificate_request_type client_certificate_request, - void* reserved); - -typedef struct grpc_ssl_server_credentials_options - grpc_ssl_server_credentials_options; - -/** Creates an options object using a certificate config. Use this method when - the certificates and keys of the SSL server will not change during the - server's lifetime. - - Takes ownership of the certificate_config parameter. */ -GRPCAPI grpc_ssl_server_credentials_options* -grpc_ssl_server_credentials_create_options_using_config( - grpc_ssl_client_certificate_request_type client_certificate_request, - grpc_ssl_server_certificate_config* certificate_config); - -/** Creates an options object using a certificate config fetcher. Use this - method to reload the certificates and keys of the SSL server without - interrupting the operation of the server. Initial certificate config will be - fetched during server initialization. - - user_data parameter, if not NULL, contains opaque data which will be passed - to the fetcher (see definition of - grpc_ssl_server_certificate_config_callback). */ -GRPCAPI grpc_ssl_server_credentials_options* -grpc_ssl_server_credentials_create_options_using_config_fetcher( - grpc_ssl_client_certificate_request_type client_certificate_request, - grpc_ssl_server_certificate_config_callback cb, void* user_data); - -/** Destroys a grpc_ssl_server_credentials_options object. */ -GRPCAPI void grpc_ssl_server_credentials_options_destroy( - grpc_ssl_server_credentials_options* options); - -/** Creates an SSL server_credentials object using the provided options struct. - - Takes ownership of the options parameter. */ -GRPCAPI grpc_server_credentials* -grpc_ssl_server_credentials_create_with_options( - grpc_ssl_server_credentials_options* options); - -/** --- Call specific credentials. --- */ - -/** Sets a credentials to a call. Can only be called on the client side before - grpc_call_start_batch. */ -GRPCAPI grpc_call_error grpc_call_set_credentials(grpc_call* call, - grpc_call_credentials* creds); - -/** --- Auth Metadata Processing --- */ - -/** Callback function that is called when the metadata processing is done. - - Consumed metadata will be removed from the set of metadata available on the - call. consumed_md may be NULL if no metadata has been consumed. - - Response metadata will be set on the response. response_md may be NULL. - - status is GRPC_STATUS_OK for success or a specific status for an error. - Common error status for auth metadata processing is either - GRPC_STATUS_UNAUTHENTICATED in case of an authentication failure or - GRPC_STATUS PERMISSION_DENIED in case of an authorization failure. - - error_details gives details about the error. May be NULL. */ -typedef void (*grpc_process_auth_metadata_done_cb)( - void* user_data, const grpc_metadata* consumed_md, size_t num_consumed_md, - const grpc_metadata* response_md, size_t num_response_md, - grpc_status_code status, const char* error_details); - -/** Pluggable server-side metadata processor object. */ -typedef struct { - /** The context object is read/write: it contains the properties of the - channel peer and it is the job of the process function to augment it with - properties derived from the passed-in metadata. - The lifetime of these objects is guaranteed until cb is invoked. */ - void (*process)(void* state, grpc_auth_context* context, - const grpc_metadata* md, size_t num_md, - grpc_process_auth_metadata_done_cb cb, void* user_data); - void (*destroy)(void* state); - void* state; -} grpc_auth_metadata_processor; - -GRPCAPI void grpc_server_credentials_set_auth_metadata_processor( - grpc_server_credentials* creds, grpc_auth_metadata_processor processor); - -/** --- ALTS channel/server credentials --- **/ - -/** - * Main interface for ALTS credentials options. The options will contain - * information that will be passed from grpc to TSI layer such as RPC protocol - * versions. ALTS client (channel) and server credentials will have their own - * implementation of this interface. The APIs listed in this header are - * thread-compatible. It is used for experimental purpose for now and subject - * to change. - */ -typedef struct grpc_alts_credentials_options grpc_alts_credentials_options; - -/** - * This method creates a grpc ALTS credentials client options instance. - * It is used for experimental purpose for now and subject to change. - */ -GRPCAPI grpc_alts_credentials_options* -grpc_alts_credentials_client_options_create(void); - -/** - * This method creates a grpc ALTS credentials server options instance. - * It is used for experimental purpose for now and subject to change. - */ -GRPCAPI grpc_alts_credentials_options* -grpc_alts_credentials_server_options_create(void); - -/** - * This method adds a target service account to grpc client's ALTS credentials - * options instance. It is used for experimental purpose for now and subject - * to change. - * - * - options: grpc ALTS credentials options instance. - * - service_account: service account of target endpoint. - */ -GRPCAPI void grpc_alts_credentials_client_options_add_target_service_account( - grpc_alts_credentials_options* options, const char* service_account); - -/** - * This method destroys a grpc_alts_credentials_options instance by - * de-allocating all of its occupied memory. It is used for experimental purpose - * for now and subject to change. - * - * - options: a grpc_alts_credentials_options instance that needs to be - * destroyed. - */ -GRPCAPI void grpc_alts_credentials_options_destroy( - grpc_alts_credentials_options* options); - -/** - * This method creates an ALTS channel credential object. The security - * level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. - * It is used for experimental purpose for now and subject to change. - * - * - options: grpc ALTS credentials options instance for client. - * - * It returns the created ALTS channel credential object. - */ -GRPCAPI grpc_channel_credentials* grpc_alts_credentials_create( - const grpc_alts_credentials_options* options); - -/** - * This method creates an ALTS server credential object. It is used for - * experimental purpose for now and subject to change. - * - * - options: grpc ALTS credentials options instance for server. - * - * It returns the created ALTS server credential object. - */ -GRPCAPI grpc_server_credentials* grpc_alts_server_credentials_create( - const grpc_alts_credentials_options* options); - -/** --- Local channel/server credentials --- **/ - -/** - * This method creates a local channel credential object. The security level - * of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY for UDS and - * GRPC_SECURITY_NONE for LOCAL_TCP. It is used for experimental purpose - * for now and subject to change. - * - * - type: local connection type - * - * It returns the created local channel credential object. - */ -GRPCAPI grpc_channel_credentials* grpc_local_credentials_create( - grpc_local_connect_type type); - -/** - * This method creates a local server credential object. It is used for - * experimental purpose for now and subject to change. - * - * - type: local connection type - * - * It returns the created local server credential object. - */ -GRPCAPI grpc_server_credentials* grpc_local_server_credentials_create( - grpc_local_connect_type type); - -/** --- TLS channel/server credentials --- - * It is used for experimental purpose for now and subject to change. */ - -/** - * EXPERIMENTAL API - Subject to change - * - * A struct that can be specified by callers to configure underlying TLS - * behaviors. - */ -typedef struct grpc_tls_credentials_options grpc_tls_credentials_options; - -/** - * EXPERIMENTAL API - Subject to change - * - * A struct provides ways to gain credential data that will be used in the TLS - * handshake. - */ -typedef struct grpc_tls_certificate_provider grpc_tls_certificate_provider; - -/** - * EXPERIMENTAL API - Subject to change - * - * A struct that stores the credential data presented to the peer in handshake - * to show local identity. - */ -typedef struct grpc_tls_identity_pairs grpc_tls_identity_pairs; - -/** - * EXPERIMENTAL API - Subject to change - * - * Creates a grpc_tls_identity_pairs that stores a list of identity credential - * data, including identity private key and identity certificate chain. - */ -GRPCAPI grpc_tls_identity_pairs* grpc_tls_identity_pairs_create(); - -/** - * EXPERIMENTAL API - Subject to change - * - * Adds a identity private key and a identity certificate chain to - * grpc_tls_identity_pairs. This function will make an internal copy of - * |private_key| and |cert_chain|. - */ -GRPCAPI void grpc_tls_identity_pairs_add_pair(grpc_tls_identity_pairs* pairs, - const char* private_key, - const char* cert_chain); - -/** - * EXPERIMENTAL API - Subject to change - * - * Destroys a grpc_tls_identity_pairs object. If this object is passed to a - * provider initiation function, the ownership is transferred so this function - * doesn't need to be called. Otherwise the creator of the - * grpc_tls_identity_pairs object is responsible for its destruction. - */ -GRPCAPI void grpc_tls_identity_pairs_destroy(grpc_tls_identity_pairs* pairs); - -/** - * EXPERIMENTAL API - Subject to change - * - * Creates a grpc_tls_certificate_provider that will load credential data from - * static string during initialization. This provider will always return the - * same cert data for all cert names. - * root_certificate and pem_key_cert_pairs can be nullptr, indicating the - * corresponding credential data is not needed. - * This function will make a copy of |root_certificate|. - * The ownership of |pem_key_cert_pairs| is transferred. - */ -GRPCAPI grpc_tls_certificate_provider* -grpc_tls_certificate_provider_static_data_create( - const char* root_certificate, grpc_tls_identity_pairs* pem_key_cert_pairs); - -/** - * EXPERIMENTAL API - Subject to change - * - * Creates a grpc_tls_certificate_provider that will watch the credential - * changes on the file system. This provider will always return the up-to-date - * cert data for all the cert names callers set through - * |grpc_tls_credentials_options|. Note that this API only supports one key-cert - * file and hence one set of identity key-cert pair, so SNI(Server Name - * Indication) is not supported. - * - private_key_path is the file path of the private key. This must be set if - * |identity_certificate_path| is set. Otherwise, it could be null if no - * identity credentials are needed. - * - identity_certificate_path is the file path of the identity certificate - * chain. This must be set if |private_key_path| is set. Otherwise, it could - * be null if no identity credentials are needed. - * - root_cert_path is the file path to the root certificate bundle. This - * may be null if no root certs are needed. - * - refresh_interval_sec is the refreshing interval that we will check the - * files for updates. - * It does not take ownership of parameters. - */ -GRPCAPI grpc_tls_certificate_provider* -grpc_tls_certificate_provider_file_watcher_create( - const char* private_key_path, const char* identity_certificate_path, - const char* root_cert_path, unsigned int refresh_interval_sec); - -/** - * EXPERIMENTAL API - Subject to change - * - * Releases a grpc_tls_certificate_provider object. The creator of the - * grpc_tls_certificate_provider object is responsible for its release. - */ -GRPCAPI void grpc_tls_certificate_provider_release( - grpc_tls_certificate_provider* provider); - -/** - * EXPERIMENTAL API - Subject to change - * - * Creates an grpc_tls_credentials_options. - */ -GRPCAPI grpc_tls_credentials_options* grpc_tls_credentials_options_create(void); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the minimum TLS version that will be negotiated during the TLS - * handshake. If not set, the underlying SSL library will set it to TLS v1.2. - */ -GRPCAPI void grpc_tls_credentials_options_set_min_tls_version( - grpc_tls_credentials_options* options, grpc_tls_version min_tls_version); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the maximum TLS version that will be negotiated during the TLS - * handshake. If not set, the underlying SSL library will set it to TLS v1.3. - */ -GRPCAPI void grpc_tls_credentials_options_set_max_tls_version( - grpc_tls_credentials_options* options, grpc_tls_version max_tls_version); - -/** - * EXPERIMENTAL API - Subject to change - * - * Copies a grpc_tls_credentials_options. - */ -GRPCAPI grpc_tls_credentials_options* grpc_tls_credentials_options_copy( - grpc_tls_credentials_options* options); - -/** - * EXPERIMENTAL API - Subject to change - * - * Destroys a grpc_tls_credentials_options. - */ -GRPCAPI void grpc_tls_credentials_options_destroy( - grpc_tls_credentials_options* options); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the credential provider in the options. - * The |options| will implicitly take a new ref to the |provider|. - */ -GRPCAPI void grpc_tls_credentials_options_set_certificate_provider( - grpc_tls_credentials_options* options, - grpc_tls_certificate_provider* provider); - -/** - * EXPERIMENTAL API - Subject to change - * - * If set, gRPC stack will keep watching the root certificates with - * name |root_cert_name|. - * If this is not set on the client side, we will use the root certificates - * stored in the default system location, since client side must provide root - * certificates in TLS. - * If this is not set on the server side, we will not watch any root certificate - * updates, and assume no root certificates needed for the server(single-side - * TLS). Default root certs on the server side is not supported. - */ -GRPCAPI void grpc_tls_credentials_options_watch_root_certs( - grpc_tls_credentials_options* options); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the name of the root certificates being watched. - * If not set, We will use a default empty string as the root certificate name. - */ -GRPCAPI void grpc_tls_credentials_options_set_root_cert_name( - grpc_tls_credentials_options* options, const char* root_cert_name); - -/** - * EXPERIMENTAL API - Subject to change - * - * If set, gRPC stack will keep watching the identity key-cert pairs - * with name |identity_cert_name|. - * This is required on the server side, and optional on the client side. - */ -GRPCAPI void grpc_tls_credentials_options_watch_identity_key_cert_pairs( - grpc_tls_credentials_options* options); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the name of the identity certificates being watched. - * If not set, We will use a default empty string as the identity certificate - * name. - */ -GRPCAPI void grpc_tls_credentials_options_set_identity_cert_name( - grpc_tls_credentials_options* options, const char* identity_cert_name); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the options of whether to request and/or verify client certs. This shall - * only be called on the server side. - */ -GRPCAPI void grpc_tls_credentials_options_set_cert_request_type( - grpc_tls_credentials_options* options, - grpc_ssl_client_certificate_request_type type); - -/** Deprecated in favor of grpc_tls_credentials_options_set_crl_provider. The - * crl provider interface provides a significantly more flexible approach to - * using CRLs. See gRFC A69 for details. - * EXPERIMENTAL API - Subject to change - * - * If set, gRPC will read all hashed x.509 CRL files in the directory and - * enforce the CRL files on all TLS handshakes. Only supported for OpenSSL - * version > 1.1. - * It is used for experimental purpose for now and subject to change. - */ -GRPCAPI void grpc_tls_credentials_options_set_crl_directory( - grpc_tls_credentials_options* options, const char* crl_directory); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the options of whether to verify server certs on the client side. - * Passing in a non-zero value indicates verifying the certs. - */ -GRPCAPI void grpc_tls_credentials_options_set_verify_server_cert( - grpc_tls_credentials_options* options, int verify_server_cert); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets whether or not a TLS server should send a list of CA names in the - * ServerHello. This list of CA names is read from the server's trust bundle, so - * that the client can use this list as a hint to know which certificate it - * should send to the server. - * - * WARNING: This API is extremely dangerous and should not be used. If the - * server's trust bundle is too large, then the TLS server will be unable to - * form a ServerHello, and hence will be unusable. The definition of "too large" - * depends on the underlying SSL library being used and on the size of the CN - * fields of the certificates in the trust bundle. - */ -GRPCAPI void grpc_tls_credentials_options_set_send_client_ca_list( - grpc_tls_credentials_options* options, bool send_client_ca_list); - -/** - * EXPERIMENTAL API - Subject to change - * - * The read-only request information exposed in a verification call. - * Callers should not directly manage the ownership of it. We will make sure it - * is always available inside verify() or cancel() call, and will destroy the - * object at the end of custom verification. - */ -typedef struct grpc_tls_custom_verification_check_request { - /* The target name of the server when the client initiates the connection. */ - /* This field will be nullptr if on the server side. */ - const char* target_name; - /* The information contained in the certificate chain sent from the peer. */ - struct peer_info { - /* The Common Name field on the peer leaf certificate. */ - const char* common_name; - /* The list of Subject Alternative Names on the peer leaf certificate. */ - struct san_names { - char** uri_names; - size_t uri_names_size; - char** dns_names; - size_t dns_names_size; - char** email_names; - size_t email_names_size; - char** ip_names; - size_t ip_names_size; - } san_names; - /* The raw peer leaf certificate. */ - const char* peer_cert; - /* The raw peer certificate chain. Note that it is not always guaranteed to - * get the peer full chain. For more, please refer to - * GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME defined in file - * grpc_security_constants.h. - * TODO(ZhenLian): Consider fixing this in the future. */ - const char* peer_cert_full_chain; - /* The verified root cert subject. - * This value will only be filled if the cryptographic peer certificate - * verification was successful */ - const char* verified_root_cert_subject; - } peer_info; -} grpc_tls_custom_verification_check_request; - -/** - * EXPERIMENTAL API - Subject to change - * - * A callback function provided by gRPC as a parameter of the |verify| function - * in grpc_tls_certificate_verifier_external. If |verify| is expected to be run - * asynchronously, the implementer of |verify| will need to invoke this callback - * with |callback_arg| and proper verification status at the end to bring the - * control back to gRPC C core. - */ -typedef void (*grpc_tls_on_custom_verification_check_done_cb)( - grpc_tls_custom_verification_check_request* request, void* callback_arg, - grpc_status_code status, const char* error_details); - -/** - * EXPERIMENTAL API - Subject to change - * - * The internal verifier type that will be used inside core. - */ -typedef struct grpc_tls_certificate_verifier grpc_tls_certificate_verifier; - -/** - * EXPERIMENTAL API - Subject to change - * - * A struct containing all the necessary functions a custom external verifier - * needs to implement to be able to be converted to an internal verifier. - */ -typedef struct grpc_tls_certificate_verifier_external { - void* user_data; - /** - * A function pointer containing the verification logic that will be - * performed after the TLS handshake is done. It could be processed - * synchronously or asynchronously. - * - If expected to be processed synchronously, the implementer should - * populate the verification result through |sync_status| and - * |sync_error_details|, and then return true. - * - If expected to be processed asynchronously, the implementer should return - * false immediately, and then in the asynchronous thread invoke |callback| - * with the verification result. The implementer MUST NOT invoke the async - * |callback| in the same thread before |verify| returns, otherwise it can - * lead to deadlocks. - * - * user_data: any argument that is passed in the user_data of - * grpc_tls_certificate_verifier_external during construction time - * can be retrieved later here. - * request: request information exposed to the function implementer. - * callback: the callback that the function implementer needs to invoke, if - * return a non-zero value. It is usually invoked when the - * asynchronous verification is done, and serves to bring the - * control back to gRPC. - * callback_arg: A pointer to the internal ExternalVerifier instance. This is - * mainly used as an argument in |callback|, if want to invoke - * |callback| in async mode. - * sync_status: indicates if a connection should be allowed. This should only - * be used if the verification check is done synchronously. - * sync_error_details: the error generated while verifying a connection. This - * should only be used if the verification check is done - * synchronously. the implementation must allocate the - * error string via gpr_malloc() or gpr_strdup(). - * return: return 0 if |verify| is expected to be executed asynchronously, - * otherwise return a non-zero value. - */ - int (*verify)(void* user_data, - grpc_tls_custom_verification_check_request* request, - grpc_tls_on_custom_verification_check_done_cb callback, - void* callback_arg, grpc_status_code* sync_status, - char** sync_error_details); - /** - * A function pointer that cleans up the caller-specified resources when the - * verifier is still running but the whole connection got cancelled. This - * could happen when the verifier is doing some async operations, and the - * whole handshaker object got destroyed because of connection time limit is - * reached, or any other reasons. In such cases, function implementers might - * want to be notified, and properly clean up some resources. - * - * user_data: any argument that is passed in the user_data of - * grpc_tls_certificate_verifier_external during construction time - * can be retrieved later here. - * request: request information exposed to the function implementer. It will - * be the same request object that was passed to verify(), and it - * tells the cancel() which request to cancel. - */ - void (*cancel)(void* user_data, - grpc_tls_custom_verification_check_request* request); - /** - * A function pointer that does some additional destruction work when the - * verifier is destroyed. This is used when the caller wants to associate some - * objects to the lifetime of external_verifier, and destroy them when - * external_verifier got destructed. For example, in C++, the class containing - * user-specified callback functions should not be destroyed before - * external_verifier, since external_verifier will invoke them while being - * used. - * Note that the caller MUST delete the grpc_tls_certificate_verifier_external - * object itself in this function, otherwise it will cause memory leaks. That - * also means the user_data has to carries at least a self pointer, for the - * callers to later delete it in destruct(). - * - * user_data: any argument that is passed in the user_data of - * grpc_tls_certificate_verifier_external during construction time - * can be retrieved later here. - */ - void (*destruct)(void* user_data); -} grpc_tls_certificate_verifier_external; - -/** - * EXPERIMENTAL API - Subject to change - * - * Converts an external verifier to an internal verifier. - * Note that we will not take the ownership of the external_verifier. Callers - * will need to delete external_verifier in its own destruct function. - */ -grpc_tls_certificate_verifier* grpc_tls_certificate_verifier_external_create( - grpc_tls_certificate_verifier_external* external_verifier); - -/** - * EXPERIMENTAL API - Subject to change - * - * Factory function for an internal verifier that won't perform any - * post-handshake verification. Note: using this solely without any other - * authentication mechanisms on the peer identity will leave your applications - * to the MITM(Man-In-The-Middle) attacks. Users should avoid doing so in - * production environments. - */ -grpc_tls_certificate_verifier* grpc_tls_certificate_verifier_no_op_create(); - -/** - * EXPERIMENTAL API - Subject to change - * - * Factory function for an internal verifier that will do the default hostname - * check. - */ -grpc_tls_certificate_verifier* grpc_tls_certificate_verifier_host_name_create(); - -/** - * EXPERIMENTAL API - Subject to change - * - * Releases a grpc_tls_certificate_verifier object. The creator of the - * grpc_tls_certificate_verifier object is responsible for its release. - */ -void grpc_tls_certificate_verifier_release( - grpc_tls_certificate_verifier* verifier); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the verifier in options. The |options| will implicitly take a new ref to - * the |verifier|. If not set on the client side, we will verify server's - * certificates, and check the default hostname. If not set on the server side, - * we will verify client's certificates. - */ -void grpc_tls_credentials_options_set_certificate_verifier( - grpc_tls_credentials_options* options, - grpc_tls_certificate_verifier* verifier); - -/** - * EXPERIMENTAL API - Subject to change - * - * Sets the options of whether to check the hostname of the peer on a per-call - * basis. This is usually used in a combination with virtual hosting at the - * client side, where each individual call on a channel can have a different - * host associated with it. - * This check is intended to verify that the host specified for the individual - * call is covered by the cert that the peer presented. - * The default is a non-zero value, which indicates performing such checks. - */ -GRPCAPI void grpc_tls_credentials_options_set_check_call_host( - grpc_tls_credentials_options* options, int check_call_host); - -/** - * EXPERIMENTAL API - Subject to change - * - * Performs the verification logic of an internal verifier. - * This is typically used when composing the internal verifiers as part of the - * custom verification. - * If |grpc_tls_certificate_verifier_verify| returns true, inspect the - * verification result through request->status and request->error_details. - * Otherwise, inspect through the parameter of |callback|. - */ -int grpc_tls_certificate_verifier_verify( - grpc_tls_certificate_verifier* verifier, - grpc_tls_custom_verification_check_request* request, - grpc_tls_on_custom_verification_check_done_cb callback, void* callback_arg, - grpc_status_code* sync_status, char** sync_error_details); - -/** - * EXPERIMENTAL API - Subject to change - * - * Performs the cancellation logic of an internal verifier. - * This is typically used when composing the internal verifiers as part of the - * custom verification. - */ -void grpc_tls_certificate_verifier_cancel( - grpc_tls_certificate_verifier* verifier, - grpc_tls_custom_verification_check_request* request); - -/** - * EXPERIMENTAL API - Subject to change - * - * Creates a TLS channel credential object based on the - * grpc_tls_credentials_options specified by callers. The - * grpc_channel_credentials will take the ownership of the |options|. The - * security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. - */ -grpc_channel_credentials* grpc_tls_credentials_create( - grpc_tls_credentials_options* options); - -/** - * EXPERIMENTAL API - Subject to change - * - * Creates a TLS server credential object based on the - * grpc_tls_credentials_options specified by callers. The - * grpc_server_credentials will take the ownership of the |options|. - */ -grpc_server_credentials* grpc_tls_server_credentials_create( - grpc_tls_credentials_options* options); - -/** - * EXPERIMENTAL API - Subject to change - * - * This method creates an insecure channel credentials object. - */ -GRPCAPI grpc_channel_credentials* grpc_insecure_credentials_create(); - -/** - * EXPERIMENTAL API - Subject to change - * - * This method creates an insecure server credentials object. - */ -GRPCAPI grpc_server_credentials* grpc_insecure_server_credentials_create(); - -/** - * EXPERIMENTAL API - Subject to change - * - * This method creates an xDS channel credentials object. - * - * Creating a channel with credentials of this type indicates that the channel - * should get credentials configuration from the xDS control plane. - * - * \a fallback_credentials are used if the channel target does not have the - * 'xds:///' scheme or if the xDS control plane does not provide information on - * how to fetch credentials dynamically. Does NOT take ownership of the \a - * fallback_credentials. (Internally takes a ref to the object.) - */ -GRPCAPI grpc_channel_credentials* grpc_xds_credentials_create( - grpc_channel_credentials* fallback_credentials); - -/** - * EXPERIMENTAL API - Subject to change - * - * This method creates an xDS server credentials object. - * - * \a fallback_credentials are used if the xDS control plane does not provide - * information on how to fetch credentials dynamically. - * - * Does NOT take ownership of the \a fallback_credentials. (Internally takes - * a ref to the object.) - */ -GRPCAPI grpc_server_credentials* grpc_xds_server_credentials_create( - grpc_server_credentials* fallback_credentials); - /** * EXPERIMENTAL - Subject to change. * An opaque type that is responsible for providing authorization policies to @@ -1302,26 +151,6 @@ grpc_authorization_policy_provider_file_watcher_create( GRPCAPI void grpc_authorization_policy_provider_release( grpc_authorization_policy_provider* provider); -/** --- TLS session key logging. --- - * Experimental API to control tls session key logging. Tls session key logging - * is expected to be used only for debugging purposes and never in production. - * Tls session key logging is only enabled when: - * At least one grpc_tls_credentials_options object is assigned a tls session - * key logging file path using the API specified below. - */ - -/** - * EXPERIMENTAL API - Subject to change. - * Configures a grpc_tls_credentials_options object with tls session key - * logging capability. TLS channels using these credentials have tls session - * key logging enabled. - * - options is the grpc_tls_credentials_options object - * - path is a string pointing to the location where TLS session keys would be - * stored. - */ -GRPCAPI void grpc_tls_credentials_options_set_tls_session_key_log_file_path( - grpc_tls_credentials_options* options, const char* path); - #ifdef __cplusplus } #endif diff --git a/include/grpc/module.modulemap b/include/grpc/module.modulemap index 7adee5b69e5..30427e21d05 100644 --- a/include/grpc/module.modulemap +++ b/include/grpc/module.modulemap @@ -6,6 +6,7 @@ header "byte_buffer.h" header "byte_buffer_reader.h" header "census.h" header "compression.h" + header "credentials.h" header "fork.h" header "grpc.h" header "grpc_audit_logging.h" @@ -37,6 +38,7 @@ header "byte_buffer.h" header "impl/propagation_bits.h" header "impl/slice_type.h" header "load_reporting.h" + header "passive_listener.h" header "slice.h" header "slice_buffer.h" header "status.h" diff --git a/include/grpc/passive_listener.h b/include/grpc/passive_listener.h new file mode 100644 index 00000000000..91fea25cc6a --- /dev/null +++ b/include/grpc/passive_listener.h @@ -0,0 +1,62 @@ +// Copyright 2024 The 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. +#ifndef GRPC_PASSIVE_LISTENER_H +#define GRPC_PASSIVE_LISTENER_H + +#include + +#include +#include +#include + +namespace grpc_core { +class Server; + +namespace experimental { +class PassiveListenerImpl; + +/// -- EXPERIMENTAL API -- +/// Interface for used for Server Endpoint injection. +class PassiveListener { + public: + virtual ~PassiveListener() = default; + /// -- EXPERIMENTAL API -- + /// + /// Takes an Endpoint for an established connection, and treats it as if the + /// connection had been accepted by the server. + /// + /// The server must be started before endpoints can be accepted. + virtual absl::Status AcceptConnectedEndpoint( + std::unique_ptr + endpoint) = 0; + + /// -- EXPERIMENTAL API -- + /// + /// Takes a connected file descriptor, and treats it as if the server had + /// accepted the connection itself. + /// + /// Returns a failure status if the server's active EventEngine does not + /// support Endpoint creation from fds. + virtual absl::Status AcceptConnectedFd(int fd) = 0; +}; + +} // namespace experimental +} // namespace grpc_core + +absl::Status grpc_server_add_passive_listener( + grpc_core::Server* server, grpc_server_credentials* credentials, + std::shared_ptr + passive_listener); + +#endif /* GRPC_PASSIVE_LISTENER_H */ diff --git a/include/grpc/support/log.h b/include/grpc/support/log.h index a118561904d..6e5cf4b7157 100644 --- a/include/grpc/support/log.h +++ b/include/grpc/support/log.h @@ -102,7 +102,7 @@ GPRAPI void gpr_assertion_failed(const char* filename, int line, #ifndef NDEBUG #define GPR_DEBUG_ASSERT(x) GPR_ASSERT(x) #else -#define GPR_DEBUG_ASSERT(x) +#define GPR_DEBUG_ASSERT(x) GPR_ASSERT(true || (x)) #endif #ifdef __cplusplus diff --git a/include/grpcpp/passive_listener.h b/include/grpcpp/passive_listener.h new file mode 100644 index 00000000000..8def9592b5e --- /dev/null +++ b/include/grpcpp/passive_listener.h @@ -0,0 +1,27 @@ +// Copyright 2024 The 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. +#ifndef GRPCPP_PASSIVE_LISTENER_H +#define GRPCPP_PASSIVE_LISTENER_H + +#include + +namespace grpc { +namespace experimental { + +using grpc_core::experimental::PassiveListener; + +} // namespace experimental +} // namespace grpc + +#endif // GRPCPP_PASSIVE_LISTENER_H diff --git a/include/grpcpp/security/server_credentials.h b/include/grpcpp/security/server_credentials.h index fe8c546190d..e3f5c2bbbfe 100644 --- a/include/grpcpp/security/server_credentials.h +++ b/include/grpcpp/security/server_credentials.h @@ -84,6 +84,7 @@ class ServerCredentials : private grpc::internal::GrpcLibrary { // Needed for access to AddPortToServer. friend class Server; // Needed for access to c_creds_. + friend class ServerBuilder; friend std::shared_ptr grpc::XdsServerCredentials( const std::shared_ptr& fallback_credentials); diff --git a/include/grpcpp/security/tls_certificate_provider.h b/include/grpcpp/security/tls_certificate_provider.h index d784292992e..3e7c9523156 100644 --- a/include/grpcpp/security/tls_certificate_provider.h +++ b/include/grpcpp/security/tls_certificate_provider.h @@ -20,6 +20,7 @@ #include #include +#include #include #include #include diff --git a/include/grpcpp/server_builder.h b/include/grpcpp/server_builder.h index e6266a90d98..eceaa5c6c73 100644 --- a/include/grpcpp/server_builder.h +++ b/include/grpcpp/server_builder.h @@ -25,13 +25,17 @@ #include #include +#include +#include #include #include #include #include #include #include +#include #include +#include #include #include #include @@ -58,6 +62,7 @@ class ExternalConnectionAcceptorImpl; class CallbackGenericService; namespace experimental { + // EXPERIMENTAL API: // Interface for a grpc server to build transports with connections created out // of band. @@ -291,6 +296,18 @@ class ServerBuilder { void EnableCallMetricRecording( experimental::ServerMetricRecorder* server_metric_recorder = nullptr); + // Creates a passive listener for Server Endpoint injection. + /// + /// \a PasiveListener lets applications provide pre-established connections + /// to gRPC Servers. The server will behave as if it accepted the connection + /// itself on its own listening addresses. + /// + /// This can be called multiple times to create passive listeners with + /// different server credentials. + ServerBuilder& AddPassiveListener( + std::shared_ptr creds, + std::unique_ptr& passive_listener); + private: ServerBuilder* builder_; }; @@ -364,6 +381,17 @@ class ServerBuilder { private: friend class grpc::testing::ServerBuilderPluginTest; + struct UnstartedPassiveListener { + std::weak_ptr + passive_listener; + std::shared_ptr credentials; + UnstartedPassiveListener( + std::weak_ptr listener, + std::shared_ptr creds) + : passive_listener(std::move(listener)), + credentials(std::move(creds)) {} + }; + struct SyncServerSettings { SyncServerSettings() : num_cqs(1), min_pollers(1), max_pollers(2), cq_timeout_msec(10000) {} @@ -388,6 +416,7 @@ class ServerBuilder { std::vector> options_; std::vector> services_; std::vector ports_; + std::vector unstarted_passive_listeners_; SyncServerSettings sync_server_settings_; diff --git a/include/grpcpp/support/callback_common.h b/include/grpcpp/support/callback_common.h index a99a47dbf4d..6ae8cfb946a 100644 --- a/include/grpcpp/support/callback_common.h +++ b/include/grpcpp/support/callback_common.h @@ -207,7 +207,9 @@ class CallbackWithSuccessTag : public grpc_completion_queue_functor { auto* ops = ops_; #endif bool do_callback = ops_->FinalizeResult(&ignored, &ok); +#ifndef NDEBUG GPR_DEBUG_ASSERT(ignored == ops); +#endif if (do_callback) { CatchingCallback(func_, ok); diff --git a/package.xml b/package.xml index 9288e08446f..f90a7d2186d 100644 --- a/package.xml +++ b/package.xml @@ -33,6 +33,7 @@ + @@ -80,6 +81,7 @@ + diff --git a/src/compiler/cpp_generator.cc b/src/compiler/cpp_generator.cc index d49ab12af9d..15470a191d3 100644 --- a/src/compiler/cpp_generator.cc +++ b/src/compiler/cpp_generator.cc @@ -20,6 +20,7 @@ #include #include +#include namespace grpc_cpp_generator { namespace { @@ -189,6 +190,7 @@ std::string GetHeaderIncludes(grpc_generator::File* file, void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars, bool is_public) { (*vars)["Method"] = method->name(); @@ -208,23 +210,25 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, *vars, "virtual ::grpc::Status $Method$(::grpc::ClientContext* context, " "const $Request$& request, $Response$* response) = 0;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "std::unique_ptr< " - "::grpc::ClientAsyncResponseReaderInterface< $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncResponseReaderInterface< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + printer->Print( + *vars, + "std::unique_ptr< " + "::grpc::ClientAsyncResponseReaderInterface< $Response$>> " + "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " + "const $Request$& request, " + "::grpc::CompletionQueue* cq) {\n"); + printer->Indent(); + printer->Print( + *vars, + "return std::unique_ptr< " + "::grpc::ClientAsyncResponseReaderInterface< $Response$>>(" + "$AsyncPrefix$$Method$Raw(context, request, cq));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } else if (ClientOnlyStreaming(method)) { printer->Print( @@ -239,25 +243,27 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, "($Method$Raw(context, response));\n"); printer->Outdent(); printer->Print("}\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncWriterInterface< $Request$>>" - " $AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "$Response$* " - "response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print(*vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncWriterInterface< $Request$>>(" - "$AsyncPrefix$$Method$Raw(context, response, " - "cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "std::unique_ptr< ::grpc::ClientAsyncWriterInterface< $Request$>>" + " $AsyncPrefix$$Method$(::grpc::ClientContext* context, " + "$Response$* " + "response, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Indent(); + printer->Print(*vars, + "return std::unique_ptr< " + "::grpc::ClientAsyncWriterInterface< $Request$>>(" + "$AsyncPrefix$$Method$Raw(context, response, " + "cq$AsyncRawArgs$));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } else if (ServerOnlyStreaming(method)) { printer->Print( @@ -272,24 +278,27 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, "($Method$Raw(context, request));\n"); printer->Outdent(); printer->Print("}\n"); - for (auto& async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncReaderInterface< $Response$>> " - "$AsyncPrefix$$Method$(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncReaderInterface< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "std::unique_ptr< ::grpc::ClientAsyncReaderInterface< " + "$Response$>> " + "$AsyncPrefix$$Method$(" + "::grpc::ClientContext* context, const $Request$& request, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Indent(); + printer->Print(*vars, + "return std::unique_ptr< " + "::grpc::ClientAsyncReaderInterface< $Response$>>(" + "$AsyncPrefix$$Method$Raw(context, request, " + "cq$AsyncRawArgs$));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } else if (method->BidiStreaming()) { printer->Print(*vars, @@ -304,36 +313,43 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, "$Method$Raw(context));\n"); printer->Outdent(); printer->Print("}\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< " - "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "std::unique_ptr< " + "::grpc::ClientAsyncReaderWriterInterface< $Request$, " + "$Response$>> " + "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Indent(); + printer->Print( + *vars, + "return std::unique_ptr< " + "::grpc::ClientAsyncReaderWriterInterface< $Request$, " + "$Response$>>(" + "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } } else { if (method->NoStreaming()) { - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncResponseReaderInterface< $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) = 0;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + printer->Print( + *vars, + "virtual ::grpc::ClientAsyncResponseReaderInterface< " + "$Response$>* " + "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " + "const $Request$& request, " + "::grpc::CompletionQueue* cq) = 0;\n"); + } } } else if (ClientOnlyStreaming(method)) { printer->Print( @@ -341,15 +357,17 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, "virtual ::grpc::ClientWriterInterface< $Request$>*" " $Method$Raw(" "::grpc::ClientContext* context, $Response$* response) = 0;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncWriterInterface< $Request$>*" - " $AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "$Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + printer->Print( + *vars, + "virtual ::grpc::ClientAsyncWriterInterface< $Request$>*" + " $AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " + "$Response$* response, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); + } } } else if (ServerOnlyStreaming(method)) { printer->Print( @@ -357,30 +375,34 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, "virtual ::grpc::ClientReaderInterface< $Response$>* " "$Method$Raw(" "::grpc::ClientContext* context, const $Request$& request) = 0;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncReaderInterface< $Response$>* " - "$AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + printer->Print( + *vars, + "virtual ::grpc::ClientAsyncReaderInterface< $Response$>* " + "$AsyncPrefix$$Method$Raw(" + "::grpc::ClientContext* context, const $Request$& request, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); + } } } else if (method->BidiStreaming()) { printer->Print(*vars, "virtual ::grpc::ClientReaderWriterInterface< $Request$, " "$Response$>* " "$Method$Raw(::grpc::ClientContext* context) = 0;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncReaderWriterInterface< " - "$Request$, $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + printer->Print( + *vars, + "virtual ::grpc::ClientAsyncReaderWriterInterface< " + "$Request$, $Response$>* " + "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); + } } } } @@ -388,6 +410,7 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer, void PrintHeaderClientMethod(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars, bool is_public) { (*vars)["Method"] = method->name(); @@ -406,21 +429,24 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer, *vars, "::grpc::Status $Method$(::grpc::ClientContext* context, " "const $Request$& request, $Response$* response) override;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) {\n"); - printer->Indent(); - printer->Print(*vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncResponseReader< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + printer->Print( + *vars, + "std::unique_ptr< ::grpc::ClientAsyncResponseReader< " + "$Response$>> " + "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " + "const $Request$& request, " + "::grpc::CompletionQueue* cq) {\n"); + printer->Indent(); + printer->Print(*vars, + "return std::unique_ptr< " + "::grpc::ClientAsyncResponseReader< $Response$>>(" + "$AsyncPrefix$$Method$Raw(context, request, cq));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } else if (ClientOnlyStreaming(method)) { printer->Print( @@ -434,23 +460,26 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer, "($Method$Raw(context, response));\n"); printer->Outdent(); printer->Print("}\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print(*vars, - "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>" - " $AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "$Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>(" - "$AsyncPrefix$$Method$Raw(context, response, " - "cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>" + " $AsyncPrefix$$Method$(::grpc::ClientContext* context, " + "$Response$* response, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Indent(); + printer->Print( + *vars, + "return std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>(" + "$AsyncPrefix$$Method$Raw(context, response, " + "cq$AsyncRawArgs$));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } else if (ServerOnlyStreaming(method)) { printer->Print( @@ -465,23 +494,26 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer, "($Method$Raw(context, request));\n"); printer->Outdent(); printer->Print("}\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> " - "$AsyncPrefix$$Method$(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> " + "$AsyncPrefix$$Method$(" + "::grpc::ClientContext* context, const $Request$& request, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Indent(); + printer->Print( + *vars, + "return std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>>(" + "$AsyncPrefix$$Method$Raw(context, request, " + "cq$AsyncRawArgs$));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } else if (method->BidiStreaming()) { printer->Print( @@ -495,79 +527,91 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer, "$Method$Raw(context));\n"); printer->Outdent(); printer->Print("}\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print(*vars, - "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " - "$Request$, $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " + "$Request$, $Response$>> " + "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Indent(); + printer->Print( + *vars, + "return std::unique_ptr< " + "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>>(" + "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n"); + printer->Outdent(); + printer->Print("}\n"); + } } } } else { if (method->NoStreaming()) { - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "::grpc::ClientAsyncResponseReader< $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) override;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + printer->Print( + *vars, + "::grpc::ClientAsyncResponseReader< $Response$>* " + "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " + "const $Request$& request, " + "::grpc::CompletionQueue* cq) override;\n"); + } } } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "::grpc::ClientWriter< $Request$>* $Method$Raw(" "::grpc::ClientContext* context, $Response$* response) " "override;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "::grpc::ClientAsyncWriter< $Request$>* $AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, $Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "::grpc::ClientAsyncWriter< $Request$>* $AsyncPrefix$$Method$Raw(" + "::grpc::ClientContext* context, $Response$* response, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); + } } } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "::grpc::ClientReader< $Response$>* $Method$Raw(" "::grpc::ClientContext* context, const $Request$& request)" " override;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "::grpc::ClientAsyncReader< $Response$>* $AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "::grpc::ClientAsyncReader< $Response$>* " + "$AsyncPrefix$$Method$Raw(" + "::grpc::ClientContext* context, const $Request$& request, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); + } } } else if (method->BidiStreaming()) { printer->Print(*vars, "::grpc::ClientReaderWriter< $Request$, $Response$>* " "$Method$Raw(::grpc::ClientContext* context) override;\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncRawArgs"] = async_prefix.raw_args; + printer->Print( + *vars, + "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " + "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); + } } } } @@ -724,31 +768,35 @@ void PrintHeaderClientMethodData(grpc_generator::Printer* printer, void PrintHeaderServerMethodSync(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); printer->Print(method->GetLeadingComments("//").c_str()); + if (params.allow_sync_server_api) { + printer->Print("virtual "); + } if (method->NoStreaming()) { printer->Print(*vars, - "virtual ::grpc::Status $Method$(" + "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " "$Response$* response);\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, - "virtual ::grpc::Status $Method$(" + "::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " "$Response$* response);\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, - "virtual ::grpc::Status $Method$(" + "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " "::grpc::ServerWriter< $Response$>* writer);\n"); } else if (method->BidiStreaming()) { printer->Print( *vars, - "virtual ::grpc::Status $Method$(" + "::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* stream);" "\n"); @@ -761,17 +809,19 @@ void PrintHeaderServerMethodSync(grpc_generator::Printer* printer, // to generate async and raw async APIs. void PrintHeaderServerAsyncMethodsHelper( grpc_generator::Printer* printer, const grpc_generator::Method* method, - std::map* vars) { + const Parameters& params, std::map* vars) { if (method->NoStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " + "$Response$* /*response*/) override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print( *vars, "void Request$Method$(" @@ -784,16 +834,18 @@ void PrintHeaderServerAsyncMethodsHelper( "request, response, new_call_cq, notification_cq, tag);\n"); printer->Print("}\n"); } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReader< $Request$>* /*reader*/, " - "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, " + "::grpc::ServerReader< $Request$>* /*reader*/, " + "$Response$* /*response*/) override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print( *vars, "void Request$Method$(" @@ -806,16 +858,18 @@ void PrintHeaderServerAsyncMethodsHelper( "context, reader, new_call_cq, notification_cq, tag);\n"); printer->Print("}\n"); } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "::grpc::ServerWriter< $Response$>* /*writer*/) override " - "{\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " + "::grpc::ServerWriter< $Response$>* /*writer*/) override " + "{\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print( *vars, "void Request$Method$(" @@ -829,16 +883,18 @@ void PrintHeaderServerAsyncMethodsHelper( "context, request, writer, new_call_cq, notification_cq, tag);\n"); printer->Print("}\n"); } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - " override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, " + "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " + " override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print( *vars, "void Request$Method$(" @@ -856,6 +912,7 @@ void PrintHeaderServerAsyncMethodsHelper( void PrintHeaderServerMethodAsync(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); // These will be disabled @@ -881,7 +938,7 @@ void PrintHeaderServerMethodAsync(grpc_generator::Printer* printer, "~WithAsyncMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); - PrintHeaderServerAsyncMethodsHelper(printer, method, vars); + PrintHeaderServerAsyncMethodsHelper(printer, method, params, vars); printer->Outdent(); printer->Print(*vars, "};\n"); } @@ -891,17 +948,19 @@ void PrintHeaderServerMethodAsync(grpc_generator::Printer* printer, // to generate callback and raw callback APIs. void PrintHeaderServerCallbackMethodsHelper( grpc_generator::Printer* printer, const grpc_generator::Method* method, - std::map* vars) { + const Parameters& params, std::map* vars) { if (method->NoStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " + "$Response$* /*response*/) override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print(*vars, "virtual ::grpc::ServerUnaryReactor* $Method$(\n" " ::grpc::CallbackServerContext* /*context*/, " @@ -909,16 +968,18 @@ void PrintHeaderServerCallbackMethodsHelper( "$RealResponse$* /*response*/)" " { return nullptr; }\n"); } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReader< $Request$>* /*reader*/, " - "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, " + "::grpc::ServerReader< $Request$>* /*reader*/, " + "$Response$* /*response*/) override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print(*vars, "virtual ::grpc::ServerReadReactor< " "$RealRequest$>* $Method$(\n" @@ -926,16 +987,18 @@ void PrintHeaderServerCallbackMethodsHelper( "/*context*/, $RealResponse$* /*response*/)" " { return nullptr; }\n"); } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "::grpc::ServerWriter< $Response$>* /*writer*/) override " - "{\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " + "::grpc::ServerWriter< $Response$>* /*writer*/) override " + "{\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print( *vars, "virtual ::grpc::ServerWriteReactor< $RealResponse$>* $Method$(\n" @@ -943,16 +1006,18 @@ void PrintHeaderServerCallbackMethodsHelper( "/*context*/, const $RealRequest$* /*request*/)" " { return nullptr; }\n"); } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - " override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, " + "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " + " override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } printer->Print( *vars, "virtual ::grpc::ServerBidiReactor< $RealRequest$, $RealResponse$>* " @@ -964,6 +1029,7 @@ void PrintHeaderServerCallbackMethodsHelper( void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); // These will be disabled @@ -1039,14 +1105,14 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "~WithCallbackMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); - PrintHeaderServerCallbackMethodsHelper(printer, method, vars); + PrintHeaderServerCallbackMethodsHelper(printer, method, params, vars); printer->Outdent(); printer->Print(*vars, "};\n"); } void PrintHeaderServerMethodRawCallback( grpc_generator::Printer* printer, const grpc_generator::Method* method, - std::map* vars) { + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); // These will be disabled (*vars)["Request"] = method->input_type_name(); @@ -1111,7 +1177,7 @@ void PrintHeaderServerMethodRawCallback( "~WithRawCallbackMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); - PrintHeaderServerCallbackMethodsHelper(printer, method, vars); + PrintHeaderServerCallbackMethodsHelper(printer, method, params, vars); printer->Outdent(); printer->Print(*vars, "};\n"); } @@ -1227,6 +1293,7 @@ void PrintHeaderServerMethodSplitStreaming( void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); @@ -1248,49 +1315,51 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer, "~WithGenericMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); - if (method->NoStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReader< $Request$>* /*reader*/, " - "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "::grpc::ServerWriter< $Response$>* /*writer*/) override " - "{\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - " override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + if (params.allow_sync_server_api) { + if (method->NoStreaming()) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " + "$Response$* /*response*/) override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } else if (ClientOnlyStreaming(method)) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, " + "::grpc::ServerReader< $Request$>* /*reader*/, " + "$Response$* /*response*/) override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } else if (ServerOnlyStreaming(method)) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " + "::grpc::ServerWriter< $Response$>* /*writer*/) override " + "{\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } else if (method->BidiStreaming()) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" + "::grpc::ServerContext* /*context*/, " + "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " + " override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + } } printer->Outdent(); printer->Print(*vars, "};\n"); @@ -1298,6 +1367,7 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer, void PrintHeaderServerMethodRaw(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); // These will be disabled @@ -1322,13 +1392,14 @@ void PrintHeaderServerMethodRaw(grpc_generator::Printer* printer, "~WithRawMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); - PrintHeaderServerAsyncMethodsHelper(printer, method, vars); + PrintHeaderServerAsyncMethodsHelper(printer, method, params, vars); printer->Outdent(); printer->Print(*vars, "};\n"); } void PrintHeaderService(grpc_generator::Printer* printer, const grpc_generator::Service* service, + const Parameters& params, std::map* vars) { (*vars)["Service"] = service->name(); @@ -1352,8 +1423,8 @@ void PrintHeaderService(grpc_generator::Printer* printer, printer->Print("virtual ~StubInterface() {}\n"); for (int i = 0; i < service->method_count(); ++i) { printer->Print(service->method(i)->GetLeadingComments("//").c_str()); - PrintHeaderClientMethodInterfaces(printer, service->method(i).get(), vars, - true); + PrintHeaderClientMethodInterfaces(printer, service->method(i).get(), params, + vars, true); printer->Print(service->method(i)->GetTrailingComments("//").c_str()); } PrintHeaderClientMethodCallbackInterfacesStart(printer, vars); @@ -1368,8 +1439,8 @@ void PrintHeaderService(grpc_generator::Printer* printer, printer->Print(" private:\n"); printer->Indent(); for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderClientMethodInterfaces(printer, service->method(i).get(), vars, - false); + PrintHeaderClientMethodInterfaces(printer, service->method(i).get(), params, + vars, false); } printer->Outdent(); printer->Print("};\n"); @@ -1382,7 +1453,8 @@ void PrintHeaderService(grpc_generator::Printer* printer, "channel, const ::grpc::StubOptions& options = " "::grpc::StubOptions());\n"); for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderClientMethod(printer, service->method(i).get(), vars, true); + PrintHeaderClientMethod(printer, service->method(i).get(), params, vars, + true); } PrintHeaderClientMethodCallbackStart(printer, vars); for (int i = 0; i < service->method_count(); ++i) { @@ -1395,7 +1467,8 @@ void PrintHeaderService(grpc_generator::Printer* printer, printer->Print("std::shared_ptr< ::grpc::ChannelInterface> channel_;\n"); printer->Print("class async async_stub_{this};\n"); for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderClientMethod(printer, service->method(i).get(), vars, false); + PrintHeaderClientMethod(printer, service->method(i).get(), params, vars, + false); } for (int i = 0; i < service->method_count(); ++i) { PrintHeaderClientMethodData(printer, service->method(i).get(), vars); @@ -1417,33 +1490,38 @@ void PrintHeaderService(grpc_generator::Printer* printer, printer->Print("Service();\n"); printer->Print("virtual ~Service();\n"); for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderServerMethodSync(printer, service->method(i).get(), vars); + PrintHeaderServerMethodSync(printer, service->method(i).get(), params, + vars); } printer->Outdent(); printer->Print("};\n"); - // Server side - Asynchronous - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodAsync(printer, service->method(i).get(), vars); - } + if (params.allow_cq_api) { + // Server side - Asynchronous + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["Idx"] = as_string(i); + PrintHeaderServerMethodAsync(printer, service->method(i).get(), params, + vars); + } - printer->Print("typedef "); + printer->Print("typedef "); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); - printer->Print(*vars, "WithAsyncMethod_$method_name$<"); - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - printer->Print(" >"); + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["method_name"] = service->method(i)->name(); + printer->Print(*vars, "WithAsyncMethod_$method_name$<"); + } + printer->Print("Service"); + for (int i = 0; i < service->method_count(); ++i) { + printer->Print(" >"); + } + printer->Print(" AsyncService;\n"); } - printer->Print(" AsyncService;\n"); // Server side - Callback for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodCallback(printer, service->method(i).get(), vars); + PrintHeaderServerMethodCallback(printer, service->method(i).get(), params, + vars); } printer->Print("typedef "); @@ -1465,88 +1543,95 @@ void PrintHeaderService(grpc_generator::Printer* printer, // Server side - Generic for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodGeneric(printer, service->method(i).get(), vars); + PrintHeaderServerMethodGeneric(printer, service->method(i).get(), params, + vars); } - // Server side - Raw - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodRaw(printer, service->method(i).get(), vars); + // Server side - Raw Async + if (params.allow_cq_api) { + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["Idx"] = as_string(i); + PrintHeaderServerMethodRaw(printer, service->method(i).get(), params, + vars); + } } // Server side - Raw Callback for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodRawCallback(printer, service->method(i).get(), vars); + PrintHeaderServerMethodRawCallback(printer, service->method(i).get(), + params, vars); } - // Server side - Streamed Unary - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodStreamedUnary(printer, service->method(i).get(), - vars); - } + if (params.allow_sync_server_api) { + // Server side - Streamed Unary + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["Idx"] = as_string(i); + PrintHeaderServerMethodStreamedUnary(printer, service->method(i).get(), + vars); + } - printer->Print("typedef "); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); - if (service->method(i)->NoStreaming()) { - printer->Print(*vars, "WithStreamedUnaryMethod_$method_name$<"); + printer->Print("typedef "); + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["method_name"] = service->method(i)->name(); + if (service->method(i)->NoStreaming()) { + printer->Print(*vars, "WithStreamedUnaryMethod_$method_name$<"); + } } - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - if (service->method(i)->NoStreaming()) { - printer->Print(" >"); + printer->Print("Service"); + for (int i = 0; i < service->method_count(); ++i) { + if (service->method(i)->NoStreaming()) { + printer->Print(" >"); + } } - } - printer->Print(" StreamedUnaryService;\n"); + printer->Print(" StreamedUnaryService;\n"); - // Server side - controlled server-side streaming - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodSplitStreaming(printer, service->method(i).get(), - vars); - } + // Server side - controlled server-side streaming + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["Idx"] = as_string(i); + PrintHeaderServerMethodSplitStreaming(printer, service->method(i).get(), + vars); + } - printer->Print("typedef "); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); - auto method = service->method(i); - if (ServerOnlyStreaming(method.get())) { - printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); + printer->Print("typedef "); + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["method_name"] = service->method(i)->name(); + auto method = service->method(i); + if (ServerOnlyStreaming(method.get())) { + printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); + } } - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - if (ServerOnlyStreaming(method.get())) { - printer->Print(" >"); + printer->Print("Service"); + for (int i = 0; i < service->method_count(); ++i) { + auto method = service->method(i); + if (ServerOnlyStreaming(method.get())) { + printer->Print(" >"); + } } - } - printer->Print(" SplitStreamedService;\n"); + printer->Print(" SplitStreamedService;\n"); - // Server side - typedef for controlled both unary and server-side streaming - printer->Print("typedef "); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); - auto method = service->method(i); - if (ServerOnlyStreaming(method.get())) { - printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); - } - if (service->method(i)->NoStreaming()) { - printer->Print(*vars, "WithStreamedUnaryMethod_$method_name$<"); + // Server side - typedef for controlled both unary and server-side streaming + printer->Print("typedef "); + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["method_name"] = service->method(i)->name(); + auto method = service->method(i); + if (ServerOnlyStreaming(method.get())) { + printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); + } + if (service->method(i)->NoStreaming()) { + printer->Print(*vars, "WithStreamedUnaryMethod_$method_name$<"); + } } - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - if (service->method(i)->NoStreaming() || - ServerOnlyStreaming(method.get())) { - printer->Print(" >"); + printer->Print("Service"); + for (int i = 0; i < service->method_count(); ++i) { + auto method = service->method(i); + if (service->method(i)->NoStreaming() || + ServerOnlyStreaming(method.get())) { + printer->Print(" >"); + } } + printer->Print(" StreamedService;\n"); } - printer->Print(" StreamedService;\n"); printer->Outdent(); printer->Print("};\n"); @@ -1573,7 +1658,7 @@ std::string GetHeaderServices(grpc_generator::File* file, } for (int i = 0; i < file->service_count(); ++i) { - PrintHeaderService(printer.get(), file->service(i).get(), &vars); + PrintHeaderService(printer.get(), file->service(i).get(), params, &vars); printer->Print("\n"); } @@ -1682,6 +1767,7 @@ std::string GetSourceIncludes(grpc_generator::File* file, void PrintSourceClientMethod(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); @@ -1729,32 +1815,35 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "(stub_->channel_.get(), stub_->rpcmethod_$Method$_, " "context, request, response, reactor);\n}\n\n"); - printer->Print(*vars, - "::grpc::ClientAsyncResponseReader< $Response$>* " - "$ns$$Service$::Stub::PrepareAsync$Method$Raw(::grpc::" - "ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) {\n"); - printer->Print(*vars, - " return " - "::grpc::internal::ClientAsyncResponseReaderHelper::Create" - "< $Response$, $Request$, ::grpc::protobuf::MessageLite, " - "::grpc::protobuf::MessageLite>" - "(channel_.get(), cq, rpcmethod_$Method$_, " - "context, request);\n" - "}\n\n"); - printer->Print(*vars, - "::grpc::ClientAsyncResponseReader< $Response$>* " - "$ns$$Service$::Stub::Async$Method$Raw(::grpc::" - "ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) {\n"); - printer->Print(*vars, - " auto* result =\n" - " this->PrepareAsync$Method$Raw(context, request, cq);\n" - " result->StartCall();\n" - " return result;\n" - "}\n\n"); + if (params.allow_cq_api) { + printer->Print(*vars, + "::grpc::ClientAsyncResponseReader< $Response$>* " + "$ns$$Service$::Stub::PrepareAsync$Method$Raw(::grpc::" + "ClientContext* context, " + "const $Request$& request, " + "::grpc::CompletionQueue* cq) {\n"); + printer->Print(*vars, + " return " + "::grpc::internal::ClientAsyncResponseReaderHelper::Create" + "< $Response$, $Request$, ::grpc::protobuf::MessageLite, " + "::grpc::protobuf::MessageLite>" + "(channel_.get(), cq, rpcmethod_$Method$_, " + "context, request);\n" + "}\n\n"); + printer->Print(*vars, + "::grpc::ClientAsyncResponseReader< $Response$>* " + "$ns$$Service$::Stub::Async$Method$Raw(::grpc::" + "ClientContext* context, " + "const $Request$& request, " + "::grpc::CompletionQueue* cq) {\n"); + printer->Print( + *vars, + " auto* result =\n" + " this->PrepareAsync$Method$Raw(context, request, cq);\n" + " result->StartCall();\n" + " return result;\n" + "}\n\n"); + } } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "::grpc::ClientWriter< $Request$>* " @@ -1781,23 +1870,25 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "context, response, reactor);\n" "}\n\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncStart"] = async_prefix.start; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncCreateArgs"] = async_prefix.create_args; - printer->Print(*vars, - "::grpc::ClientAsyncWriter< $Request$>* " - "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, $Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Print( - *vars, - " return ::grpc::internal::ClientAsyncWriterFactory< $Request$>" - "::Create(channel_.get(), cq, " - "rpcmethod_$Method$_, " - "context, response, $AsyncStart$$AsyncCreateArgs$);\n" - "}\n\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncStart"] = async_prefix.start; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncCreateArgs"] = async_prefix.create_args; + printer->Print(*vars, + "::grpc::ClientAsyncWriter< $Request$>* " + "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(" + "::grpc::ClientContext* context, $Response$* response, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Print( + *vars, + " return ::grpc::internal::ClientAsyncWriterFactory< $Request$>" + "::Create(channel_.get(), cq, " + "rpcmethod_$Method$_, " + "context, response, $AsyncStart$$AsyncCreateArgs$);\n" + "}\n\n"); + } } } else if (ServerOnlyStreaming(method)) { printer->Print( @@ -1826,24 +1917,26 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "context, request, reactor);\n" "}\n\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncStart"] = async_prefix.start; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncCreateArgs"] = async_prefix.create_args; - printer->Print( - *vars, - "::grpc::ClientAsyncReader< $Response$>* " - "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Print(*vars, - " return ::grpc::internal::ClientAsyncReaderFactory< " - "$Response$>" - "::Create(channel_.get(), cq, " - "rpcmethod_$Method$_, " - "context, request, $AsyncStart$$AsyncCreateArgs$);\n" - "}\n\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncStart"] = async_prefix.start; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncCreateArgs"] = async_prefix.create_args; + printer->Print( + *vars, + "::grpc::ClientAsyncReader< $Response$>* " + "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(" + "::grpc::ClientContext* context, const $Request$& request, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Print(*vars, + " return ::grpc::internal::ClientAsyncReaderFactory< " + "$Response$>" + "::Create(channel_.get(), cq, " + "rpcmethod_$Method$_, " + "context, request, $AsyncStart$$AsyncCreateArgs$);\n" + "}\n\n"); + } } } else if (method->BidiStreaming()) { printer->Print( @@ -1871,30 +1964,34 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "context, reactor);\n" "}\n\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncStart"] = async_prefix.start; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncCreateArgs"] = async_prefix.create_args; - printer->Print(*vars, - "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " - "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(::grpc::" - "ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Print(*vars, - " return " - "::grpc::internal::ClientAsyncReaderWriterFactory< " - "$Request$, $Response$>::Create(" - "channel_.get(), cq, " - "rpcmethod_$Method$_, " - "context, $AsyncStart$$AsyncCreateArgs$);\n" - "}\n\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncStart"] = async_prefix.start; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["AsyncCreateArgs"] = async_prefix.create_args; + printer->Print( + *vars, + "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " + "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(::grpc::" + "ClientContext* context, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); + printer->Print(*vars, + " return " + "::grpc::internal::ClientAsyncReaderWriterFactory< " + "$Request$, $Response$>::Create(" + "channel_.get(), cq, " + "rpcmethod_$Method$_, " + "context, $AsyncStart$$AsyncCreateArgs$);\n" + "}\n\n"); + } } } } void PrintSourceServerMethod(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); @@ -1904,6 +2001,9 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer, "::grpc::Status $ns$$Service$::Service::$Method$(" "::grpc::ServerContext* context, " "const $Request$* request, $Response$* response) {\n"); + if (!params.allow_sync_server_api) { + printer->Print(" abort();\n"); + } printer->Print(" (void) context;\n"); printer->Print(" (void) request;\n"); printer->Print(" (void) response;\n"); @@ -1917,6 +2017,9 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer, "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " "$Response$* response) {\n"); + if (!params.allow_sync_server_api) { + printer->Print(" abort();\n"); + } printer->Print(" (void) context;\n"); printer->Print(" (void) reader;\n"); printer->Print(" (void) response;\n"); @@ -1930,6 +2033,9 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer, "::grpc::ServerContext* context, " "const $Request$* request, " "::grpc::ServerWriter< $Response$>* writer) {\n"); + if (!params.allow_sync_server_api) { + printer->Print(" abort();\n"); + } printer->Print(" (void) context;\n"); printer->Print(" (void) request;\n"); printer->Print(" (void) writer;\n"); @@ -1943,6 +2049,9 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer, "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* " "stream) {\n"); + if (!params.allow_sync_server_api) { + printer->Print(" abort();\n"); + } printer->Print(" (void) context;\n"); printer->Print(" (void) stream;\n"); printer->Print( @@ -1954,6 +2063,7 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer, void PrintSourceService(grpc_generator::Printer* printer, const grpc_generator::Service* service, + const Parameters& params, std::map* vars) { (*vars)["Service"] = service->name(); @@ -2011,7 +2121,7 @@ void PrintSourceService(grpc_generator::Printer* printer, for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); - PrintSourceClientMethod(printer, service->method(i).get(), vars); + PrintSourceClientMethod(printer, service->method(i).get(), params, vars); } printer->Print(*vars, "$ns$$Service$::Service::Service() {\n"); @@ -2087,7 +2197,7 @@ void PrintSourceService(grpc_generator::Printer* printer, "}\n\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); - PrintSourceServerMethod(printer, service->method(i).get(), vars); + PrintSourceServerMethod(printer, service->method(i).get(), params, vars); } } @@ -2113,7 +2223,7 @@ std::string GetSourceServices(grpc_generator::File* file, } for (int i = 0; i < file->service_count(); ++i) { - PrintSourceService(printer.get(), file->service(i).get(), &vars); + PrintSourceService(printer.get(), file->service(i).get(), params, &vars); printer->Print("\n"); } } @@ -2224,6 +2334,7 @@ std::string GetMockIncludes(grpc_generator::File* file, void PrintMockClientMethods(grpc_generator::Printer* printer, const grpc_generator::Method* method, + const Parameters& params, std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); @@ -2240,14 +2351,16 @@ void PrintMockClientMethods(grpc_generator::Printer* printer, *vars, "MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, " "const $Request$& request, $Response$* response));\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "MOCK_METHOD3($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncResponseReaderInterface< $Response$>*" - "(::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq));\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + printer->Print( + *vars, + "MOCK_METHOD3($AsyncPrefix$$Method$Raw, " + "::grpc::ClientAsyncResponseReaderInterface< $Response$>*" + "(::grpc::ClientContext* context, const $Request$& request, " + "::grpc::CompletionQueue* cq));\n"); + } } } else if (ClientOnlyStreaming(method)) { printer->Print( @@ -2255,16 +2368,18 @@ void PrintMockClientMethods(grpc_generator::Printer* printer, "MOCK_METHOD2($Method$Raw, " "::grpc::ClientWriterInterface< $Request$>*" "(::grpc::ClientContext* context, $Response$* response));\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["MockArgs"] = - std::to_string(3 + async_prefix.extra_method_param_count); - printer->Print(*vars, - "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncWriterInterface< $Request$>*" - "(::grpc::ClientContext* context, $Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["MockArgs"] = + std::to_string(3 + async_prefix.extra_method_param_count); + printer->Print(*vars, + "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " + "::grpc::ClientAsyncWriterInterface< $Request$>*" + "(::grpc::ClientContext* context, $Response$* response, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n"); + } } } else if (ServerOnlyStreaming(method)) { printer->Print( @@ -2272,17 +2387,19 @@ void PrintMockClientMethods(grpc_generator::Printer* printer, "MOCK_METHOD2($Method$Raw, " "::grpc::ClientReaderInterface< $Response$>*" "(::grpc::ClientContext* context, const $Request$& request));\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["MockArgs"] = - std::to_string(3 + async_prefix.extra_method_param_count); - printer->Print( - *vars, - "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncReaderInterface< $Response$>*" - "(::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["MockArgs"] = + std::to_string(3 + async_prefix.extra_method_param_count); + printer->Print( + *vars, + "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " + "::grpc::ClientAsyncReaderInterface< $Response$>*" + "(::grpc::ClientContext* context, const $Request$& request, " + "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n"); + } } } else if (method->BidiStreaming()) { printer->Print( @@ -2290,24 +2407,27 @@ void PrintMockClientMethods(grpc_generator::Printer* printer, "MOCK_METHOD1($Method$Raw, " "::grpc::ClientReaderWriterInterface< $Request$, $Response$>*" "(::grpc::ClientContext* context));\n"); - for (auto async_prefix : async_prefixes) { - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["MockArgs"] = - std::to_string(2 + async_prefix.extra_method_param_count); - printer->Print( - *vars, - "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncReaderWriterInterface<$Request$, " - "$Response$>*" - "(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq" - "$AsyncMethodParams$));\n"); + if (params.allow_cq_api) { + for (const auto& async_prefix : async_prefixes) { + (*vars)["AsyncPrefix"] = async_prefix.prefix; + (*vars)["AsyncMethodParams"] = async_prefix.method_params; + (*vars)["MockArgs"] = + std::to_string(2 + async_prefix.extra_method_param_count); + printer->Print( + *vars, + "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " + "::grpc::ClientAsyncReaderWriterInterface<$Request$, " + "$Response$>*" + "(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq" + "$AsyncMethodParams$));\n"); + } } } } void PrintMockService(grpc_generator::Printer* printer, const grpc_generator::Service* service, + const Parameters& params, std::map* vars) { (*vars)["Service"] = service->name(); @@ -2316,7 +2436,7 @@ void PrintMockService(grpc_generator::Printer* printer, " public:\n"); printer->Indent(); for (int i = 0; i < service->method_count(); ++i) { - PrintMockClientMethods(printer, service->method(i).get(), vars); + PrintMockClientMethods(printer, service->method(i).get(), params, vars); } printer->Outdent(); printer->Print("};\n"); @@ -2342,7 +2462,7 @@ std::string GetMockServices(grpc_generator::File* file, } for (int i = 0; i < file->service_count(); i++) { - PrintMockService(printer.get(), file->service(i).get(), &vars); + PrintMockService(printer.get(), file->service(i).get(), params, &vars); printer->Print("\n"); } diff --git a/src/compiler/cpp_generator.h b/src/compiler/cpp_generator.h index 4032876cef8..14e8f129af5 100644 --- a/src/compiler/cpp_generator.h +++ b/src/compiler/cpp_generator.h @@ -64,6 +64,10 @@ struct Parameters { std::string message_header_extension; // Whether to include headers corresponding to imports in source file. bool include_import_headers; + // Whether to expose synchronous server API. + bool allow_sync_server_api; + // Whether to generate completion queue API. + bool allow_cq_api; }; // Return the prologue of the generated header file. diff --git a/src/compiler/cpp_plugin.h b/src/compiler/cpp_plugin.h index 9c8c4bd2474..1e356e9421d 100644 --- a/src/compiler/cpp_plugin.h +++ b/src/compiler/cpp_plugin.h @@ -65,6 +65,8 @@ class CppGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { generator_parameters.use_system_headers = true; generator_parameters.generate_mock_code = false; generator_parameters.include_import_headers = false; + generator_parameters.allow_sync_server_api = true; + generator_parameters.allow_cq_api = true; ProtoBufFile pbfile(file); @@ -95,6 +97,24 @@ class CppGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { *error = std::string("Invalid parameter: ") + *parameter_string; return false; } + } else if (param[0] == "allow_sync_server_api") { + if (param[1] == "true") { + generator_parameters.allow_sync_server_api = true; + } else if (param[1] == "false") { + generator_parameters.allow_sync_server_api = false; + } else { + *error = std::string("Invalid parameter: ") + *parameter_string; + return false; + } + } else if (param[0] == "allow_cq_api") { + if (param[1] == "true") { + generator_parameters.allow_cq_api = true; + } else if (param[1] == "false") { + generator_parameters.allow_cq_api = false; + } else { + *error = std::string("Invalid parameter: ") + *parameter_string; + return false; + } } else if (param[0] == "gmock_search_path") { generator_parameters.gmock_search_path = param[1]; } else if (param[0] == "additional_header_includes") { diff --git a/src/core/BUILD b/src/core/BUILD index 437735b143f..14577b9f67e 100644 --- a/src/core/BUILD +++ b/src/core/BUILD @@ -3655,6 +3655,7 @@ grpc_cc_library( "validation_errors", "//:alts_util", "//:gpr", + "//:grpc_core_credentials_header", "//:ref_counted_ptr", ], ) @@ -3808,6 +3809,7 @@ grpc_cc_library( "//:exec_ctx", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:handshaker", "//:iomgr", @@ -3846,6 +3848,7 @@ grpc_cc_library( "//:exec_ctx", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:handshaker", "//:iomgr", @@ -3905,6 +3908,7 @@ grpc_cc_library( "//:gpr", "//:grpc_base", "//:grpc_client_channel", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:handshaker", "//:iomgr", @@ -3948,6 +3952,7 @@ grpc_cc_library( "//:exec_ctx", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:grpc_trace", "//:handshaker", @@ -4004,6 +4009,7 @@ grpc_cc_library( "//:gpr", "//:grpc_alts_credentials", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_jwt_credentials", "//:grpc_public_hdrs", "//:grpc_security_base", @@ -4078,6 +4084,7 @@ grpc_cc_library( "//:exec_ctx", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_credentials_util", "//:grpc_public_hdrs", "//:grpc_security_base", @@ -4117,6 +4124,7 @@ grpc_cc_library( "//:exec_ctx", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:grpc_trace", "//:promise", @@ -4164,6 +4172,7 @@ grpc_cc_library( "//:api_trace", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_credentials_util", "//:grpc_security_base", "//:grpc_trace", @@ -4219,6 +4228,7 @@ grpc_cc_library( "time", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_credentials_util", "//:grpc_security_base", "//:httpcli", @@ -4255,6 +4265,7 @@ grpc_cc_library( "//:exec_ctx", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:handshaker", "//:iomgr", @@ -5143,6 +5154,7 @@ grpc_cc_library( "//:gpr", "//:grpc_base", "//:grpc_client_channel", + "//:grpc_core_credentials_header", "//:grpc_credentials_util", "//:grpc_public_hdrs", "//:grpc_security_base", @@ -5222,6 +5234,7 @@ grpc_cc_library( "//:exec_ctx", "//:gpr", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_public_hdrs", "//:grpc_security_base", "//:grpc_service_config_impl", @@ -5256,6 +5269,7 @@ grpc_cc_library( "//:config", "//:gpr", "//:gpr_platform", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:ref_counted_ptr", ], @@ -6451,7 +6465,6 @@ grpc_cc_library( "//:endpoint_addresses", "//:gpr", "//:grpc_base", - "//:grpc_client_channel", "//:grpc_public_hdrs", "//:grpc_resolver", "//:grpc_service_config_impl", @@ -6787,6 +6800,8 @@ grpc_cc_library( "connection_quota", "error", "error_utils", + "event_engine_extensions", + "event_engine_query_extensions", "grpc_insecure_credentials", "handshaker_registry", "iomgr_fwd", @@ -6967,6 +6982,7 @@ grpc_cc_library( "//:gpr", "//:gpr_platform", "//:grpc_base", + "//:grpc_core_credentials_header", "//:grpc_security_base", "//:grpc_trace", "//:httpcli", @@ -7341,7 +7357,6 @@ grpc_cc_library( ], deps = [ "1999", - "call_final_info", "for_each", "if", "latch", @@ -7353,6 +7368,7 @@ grpc_cc_library( "status_flag", "try_seq", "//:gpr", + "//:promise", ], ) diff --git a/src/core/client_channel/client_channel_filter.cc b/src/core/client_channel/client_channel_filter.cc index 16f94347e4e..b7d4d6d4952 100644 --- a/src/core/client_channel/client_channel_filter.cc +++ b/src/core/client_channel/client_channel_filter.cc @@ -644,7 +644,9 @@ class ClientChannelFilter::SubchannelWrapper final chand, this, subchannel_.get()); } GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "SubchannelWrapper"); +#ifndef NDEBUG GPR_DEBUG_ASSERT(chand_->work_serializer_->RunningInWorkSerializer()); +#endif if (chand_->channelz_node_ != nullptr) { auto* subchannel_node = subchannel_->channelz_node(); if (subchannel_node != nullptr) { diff --git a/src/core/ext/filters/backend_metrics/backend_metric_filter.cc b/src/core/ext/filters/backend_metrics/backend_metric_filter.cc index 33566871cdf..c3ce55921d8 100644 --- a/src/core/ext/filters/backend_metrics/backend_metric_filter.cc +++ b/src/core/ext/filters/backend_metrics/backend_metric_filter.cc @@ -34,6 +34,7 @@ #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/context.h" +#include "src/core/lib/channel/promise_based_filter.h" #include "src/core/lib/config/core_configuration.h" #include "src/core/lib/debug/trace.h" #include "src/core/lib/experiments/experiments.h" @@ -121,9 +122,9 @@ const grpc_channel_filter BackendMetricFilter::kFilter = MakePromiseBasedFilter( "backend_metric"); -absl::StatusOr BackendMetricFilter::Create( - const ChannelArgs&, ChannelFilter::Args) { - return BackendMetricFilter(); +absl::StatusOr> +BackendMetricFilter::Create(const ChannelArgs&, ChannelFilter::Args) { + return std::make_unique(); } void BackendMetricFilter::Call::OnServerTrailingMetadata(ServerMetadata& md) { diff --git a/src/core/ext/filters/backend_metrics/backend_metric_filter.h b/src/core/ext/filters/backend_metrics/backend_metric_filter.h index 2c71a9d19cb..d97b0c8cb65 100644 --- a/src/core/ext/filters/backend_metrics/backend_metric_filter.h +++ b/src/core/ext/filters/backend_metrics/backend_metric_filter.h @@ -35,8 +35,8 @@ class BackendMetricFilter : public ImplementChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create(const ChannelArgs& args, - ChannelFilter::Args); + static absl::StatusOr> Create( + const ChannelArgs& args, ChannelFilter::Args); class Call { public: diff --git a/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.cc b/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.cc index 7d7757ac081..d189d4080a7 100644 --- a/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.cc +++ b/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.cc @@ -25,6 +25,7 @@ #include "absl/base/thread_annotations.h" #include "absl/meta/type_traits.h" #include "absl/random/random.h" +#include "absl/status/statusor.h" #include "absl/types/optional.h" #include @@ -133,18 +134,17 @@ struct LegacyMaxAgeFilter::Config { // will be removed at that time also, so just disable the deprecation warning // for now. ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING -absl::StatusOr LegacyClientIdleFilter::Create( - const ChannelArgs& args, ChannelFilter::Args filter_args) { - LegacyClientIdleFilter filter(filter_args.channel_stack(), - GetClientIdleTimeout(args)); - return absl::StatusOr(std::move(filter)); +absl::StatusOr> +LegacyClientIdleFilter::Create(const ChannelArgs& args, + ChannelFilter::Args filter_args) { + return std::make_unique(filter_args.channel_stack(), + GetClientIdleTimeout(args)); } -absl::StatusOr LegacyMaxAgeFilter::Create( +absl::StatusOr> LegacyMaxAgeFilter::Create( const ChannelArgs& args, ChannelFilter::Args filter_args) { - LegacyMaxAgeFilter filter(filter_args.channel_stack(), - Config::FromChannelArgs(args)); - return absl::StatusOr(std::move(filter)); + return std::make_unique(filter_args.channel_stack(), + Config::FromChannelArgs(args)); } ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING diff --git a/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.h b/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.h index 8e06505d732..8e6215cebba 100644 --- a/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.h +++ b/src/core/ext/filters/channel_idle/legacy_channel_idle_filter.h @@ -42,6 +42,11 @@ namespace grpc_core { class LegacyChannelIdleFilter : public ChannelFilter { public: + LegacyChannelIdleFilter(grpc_channel_stack* channel_stack, + Duration client_idle_timeout) + : channel_stack_(channel_stack), + client_idle_timeout_(client_idle_timeout) {} + ~LegacyChannelIdleFilter() override = default; LegacyChannelIdleFilter(const LegacyChannelIdleFilter&) = delete; @@ -59,11 +64,6 @@ class LegacyChannelIdleFilter : public ChannelFilter { using SingleSetActivityPtr = SingleSetPtr; - LegacyChannelIdleFilter(grpc_channel_stack* channel_stack, - Duration client_idle_timeout) - : channel_stack_(channel_stack), - client_idle_timeout_(client_idle_timeout) {} - grpc_channel_stack* channel_stack() { return channel_stack_; }; virtual void Shutdown(); @@ -94,10 +94,9 @@ class LegacyClientIdleFilter final : public LegacyChannelIdleFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); - private: using LegacyChannelIdleFilter::LegacyChannelIdleFilter; }; @@ -106,9 +105,12 @@ class LegacyMaxAgeFilter final : public LegacyChannelIdleFilter { static const grpc_channel_filter kFilter; struct Config; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + LegacyMaxAgeFilter(grpc_channel_stack* channel_stack, + const Config& max_age_config); + void PostInit() override; private: @@ -128,9 +130,6 @@ class LegacyMaxAgeFilter final : public LegacyChannelIdleFilter { LegacyMaxAgeFilter* filter_; }; - LegacyMaxAgeFilter(grpc_channel_stack* channel_stack, - const Config& max_age_config); - void Shutdown() override; SingleSetActivityPtr max_age_activity_; diff --git a/src/core/ext/filters/deadline/deadline_filter.cc b/src/core/ext/filters/deadline/deadline_filter.cc index 588827b9584..a2dc24594e2 100644 --- a/src/core/ext/filters/deadline/deadline_filter.cc +++ b/src/core/ext/filters/deadline/deadline_filter.cc @@ -370,8 +370,9 @@ const grpc_channel_filter grpc_server_deadline_filter = { return next_promise_factory(std::move(call_args)); }, [](grpc_channel_element*, grpc_core::CallSpineInterface* spine) { - spine->client_initial_metadata().receiver.InterceptAndMap( - [](grpc_core::ClientMetadataHandle md) { + grpc_core::DownCast(spine) + ->client_initial_metadata() + .receiver.InterceptAndMap([](grpc_core::ClientMetadataHandle md) { auto deadline = md->get(grpc_core::GrpcTimeoutMetadata()); if (deadline.has_value()) { grpc_core::GetContext()->UpdateDeadline( diff --git a/src/core/ext/filters/fault_injection/fault_injection_filter.cc b/src/core/ext/filters/fault_injection/fault_injection_filter.cc index 2464d01d7db..87d5a4d2f1f 100644 --- a/src/core/ext/filters/fault_injection/fault_injection_filter.cc +++ b/src/core/ext/filters/fault_injection/fault_injection_filter.cc @@ -29,6 +29,7 @@ #include "absl/meta/type_traits.h" #include "absl/status/status.h" +#include "absl/status/statusor.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" @@ -135,16 +136,16 @@ class FaultInjectionFilter::InjectionDecision { FaultHandle active_fault_{false}; }; -absl::StatusOr FaultInjectionFilter::Create( - const ChannelArgs&, ChannelFilter::Args filter_args) { - return FaultInjectionFilter(filter_args); +absl::StatusOr> +FaultInjectionFilter::Create(const ChannelArgs&, + ChannelFilter::Args filter_args) { + return std::make_unique(filter_args); } FaultInjectionFilter::FaultInjectionFilter(ChannelFilter::Args filter_args) : index_(filter_args.instance_id()), service_config_parser_index_( - FaultInjectionServiceConfigParser::ParserIndex()), - mu_(new Mutex) {} + FaultInjectionServiceConfigParser::ParserIndex()) {} // Construct a promise for one call. ArenaPromise FaultInjectionFilter::Call::OnClientInitialMetadata( @@ -226,7 +227,7 @@ FaultInjectionFilter::MakeInjectionDecision( bool delay_request = delay != Duration::Zero(); bool abort_request = abort_code != GRPC_STATUS_OK; if (delay_request || abort_request) { - MutexLock lock(mu_.get()); + MutexLock lock(&mu_); if (delay_request) { delay_request = UnderFraction(&delay_rand_generator_, delay_percentage_numerator, diff --git a/src/core/ext/filters/fault_injection/fault_injection_filter.h b/src/core/ext/filters/fault_injection/fault_injection_filter.h index e2918e854f5..b6b1b811cde 100644 --- a/src/core/ext/filters/fault_injection/fault_injection_filter.h +++ b/src/core/ext/filters/fault_injection/fault_injection_filter.h @@ -45,9 +45,11 @@ class FaultInjectionFilter public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + explicit FaultInjectionFilter(ChannelFilter::Args filter_args); + // Construct a promise for one call. class Call { public: @@ -61,8 +63,6 @@ class FaultInjectionFilter }; private: - explicit FaultInjectionFilter(ChannelFilter::Args filter_args); - class InjectionDecision; InjectionDecision MakeInjectionDecision( const ClientMetadata& initial_metadata); @@ -70,7 +70,7 @@ class FaultInjectionFilter // The relative index of instances of the same filter. size_t index_; const size_t service_config_parser_index_; - std::unique_ptr mu_; + Mutex mu_; absl::InsecureBitGen abort_rand_generator_ ABSL_GUARDED_BY(mu_); absl::InsecureBitGen delay_rand_generator_ ABSL_GUARDED_BY(mu_); }; diff --git a/src/core/ext/filters/http/client/http_client_filter.cc b/src/core/ext/filters/http/client/http_client_filter.cc index ac8004cdd3e..390df545efe 100644 --- a/src/core/ext/filters/http/client/http_client_filter.cc +++ b/src/core/ext/filters/http/client/http_client_filter.cc @@ -27,6 +27,7 @@ #include #include "absl/status/status.h" +#include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" @@ -136,16 +137,16 @@ HttpClientFilter::HttpClientFilter(HttpSchemeMetadata::ValueType scheme, Slice user_agent, bool test_only_use_put_requests) : scheme_(scheme), - user_agent_(std::move(user_agent)), - test_only_use_put_requests_(test_only_use_put_requests) {} + test_only_use_put_requests_(test_only_use_put_requests), + user_agent_(std::move(user_agent)) {} -absl::StatusOr HttpClientFilter::Create( +absl::StatusOr> HttpClientFilter::Create( const ChannelArgs& args, ChannelFilter::Args) { auto* transport = args.GetObject(); if (transport == nullptr) { return absl::InvalidArgumentError("HttpClientFilter needs a transport"); } - return HttpClientFilter( + return std::make_unique( SchemeFromArgs(args), UserAgentFromArgs(args, transport->GetTransportName()), args.GetInt(GRPC_ARG_TEST_ONLY_USE_PUT_REQUESTS).value_or(false)); diff --git a/src/core/ext/filters/http/client/http_client_filter.h b/src/core/ext/filters/http/client/http_client_filter.h index dbfa9f7f2d0..f5d7875da5e 100644 --- a/src/core/ext/filters/http/client/http_client_filter.h +++ b/src/core/ext/filters/http/client/http_client_filter.h @@ -35,9 +35,12 @@ class HttpClientFilter : public ImplementChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + HttpClientFilter(HttpSchemeMetadata::ValueType scheme, Slice user_agent, + bool test_only_use_put_requests); + class Call { public: void OnClientInitialMetadata(ClientMetadata& md, HttpClientFilter* filter); @@ -49,12 +52,9 @@ class HttpClientFilter : public ImplementChannelFilter { }; private: - HttpClientFilter(HttpSchemeMetadata::ValueType scheme, Slice user_agent, - bool test_only_use_put_requests); - HttpSchemeMetadata::ValueType scheme_; - Slice user_agent_; bool test_only_use_put_requests_; + Slice user_agent_; }; // A test-only channel arg to allow testing gRPC Core server behavior on PUT diff --git a/src/core/ext/filters/http/client_authority_filter.cc b/src/core/ext/filters/http/client_authority_filter.cc index 3df6d275f6a..1d5258493e4 100644 --- a/src/core/ext/filters/http/client_authority_filter.cc +++ b/src/core/ext/filters/http/client_authority_filter.cc @@ -43,8 +43,8 @@ const NoInterceptor ClientAuthorityFilter::Call::OnClientToServerMessage; const NoInterceptor ClientAuthorityFilter::Call::OnServerToClientMessage; const NoInterceptor ClientAuthorityFilter::Call::OnFinalize; -absl::StatusOr ClientAuthorityFilter::Create( - const ChannelArgs& args, ChannelFilter::Args) { +absl::StatusOr> +ClientAuthorityFilter::Create(const ChannelArgs& args, ChannelFilter::Args) { absl::optional default_authority = args.GetString(GRPC_ARG_DEFAULT_AUTHORITY); if (!default_authority.has_value()) { @@ -52,7 +52,8 @@ absl::StatusOr ClientAuthorityFilter::Create( "GRPC_ARG_DEFAULT_AUTHORITY string channel arg. not found. Note that " "direct channels must explicitly specify a value for this argument."); } - return ClientAuthorityFilter(Slice::FromCopiedString(*default_authority)); + return std::make_unique( + Slice::FromCopiedString(*default_authority)); } void ClientAuthorityFilter::Call::OnClientInitialMetadata( diff --git a/src/core/ext/filters/http/client_authority_filter.h b/src/core/ext/filters/http/client_authority_filter.h index 064e0a0a450..44229c6cdde 100644 --- a/src/core/ext/filters/http/client_authority_filter.h +++ b/src/core/ext/filters/http/client_authority_filter.h @@ -39,8 +39,11 @@ class ClientAuthorityFilter final public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create(const ChannelArgs& args, - ChannelFilter::Args); + static absl::StatusOr> Create( + const ChannelArgs& args, ChannelFilter::Args); + + explicit ClientAuthorityFilter(Slice default_authority) + : default_authority_(std::move(default_authority)) {} class Call { public: @@ -54,8 +57,6 @@ class ClientAuthorityFilter final }; private: - explicit ClientAuthorityFilter(Slice default_authority) - : default_authority_(std::move(default_authority)) {} Slice default_authority_; }; diff --git a/src/core/ext/filters/http/message_compress/compression_filter.cc b/src/core/ext/filters/http/message_compress/compression_filter.cc index c9b3acaf1f7..1ad6081ffac 100644 --- a/src/core/ext/filters/http/message_compress/compression_filter.cc +++ b/src/core/ext/filters/http/message_compress/compression_filter.cc @@ -72,14 +72,14 @@ const grpc_channel_filter ServerCompressionFilter::kFilter = kFilterExaminesInboundMessages | kFilterExaminesOutboundMessages>("compression"); -absl::StatusOr ClientCompressionFilter::Create( - const ChannelArgs& args, ChannelFilter::Args) { - return ClientCompressionFilter(args); +absl::StatusOr> +ClientCompressionFilter::Create(const ChannelArgs& args, ChannelFilter::Args) { + return std::make_unique(args); } -absl::StatusOr ServerCompressionFilter::Create( - const ChannelArgs& args, ChannelFilter::Args) { - return ServerCompressionFilter(args); +absl::StatusOr> +ServerCompressionFilter::Create(const ChannelArgs& args, ChannelFilter::Args) { + return std::make_unique(args); } ChannelCompression::ChannelCompression(const ChannelArgs& args) diff --git a/src/core/ext/filters/http/message_compress/compression_filter.h b/src/core/ext/filters/http/message_compress/compression_filter.h index adf9fb49355..99e57a0ac1d 100644 --- a/src/core/ext/filters/http/message_compress/compression_filter.h +++ b/src/core/ext/filters/http/message_compress/compression_filter.h @@ -110,9 +110,12 @@ class ClientCompressionFilter final public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + explicit ClientCompressionFilter(const ChannelArgs& args) + : compression_engine_(args) {} + // Construct a promise for one call. class Call { public: @@ -135,9 +138,6 @@ class ClientCompressionFilter final }; private: - explicit ClientCompressionFilter(const ChannelArgs& args) - : compression_engine_(args) {} - ChannelCompression compression_engine_; }; @@ -146,9 +146,12 @@ class ServerCompressionFilter final public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + explicit ServerCompressionFilter(const ChannelArgs& args) + : compression_engine_(args) {} + // Construct a promise for one call. class Call { public: @@ -171,9 +174,6 @@ class ServerCompressionFilter final }; private: - explicit ServerCompressionFilter(const ChannelArgs& args) - : compression_engine_(args) {} - ChannelCompression compression_engine_; }; diff --git a/src/core/ext/filters/http/server/http_server_filter.cc b/src/core/ext/filters/http/server/http_server_filter.cc index 775eebcb1d3..925cc73c23e 100644 --- a/src/core/ext/filters/http/server/http_server_filter.cc +++ b/src/core/ext/filters/http/server/http_server_filter.cc @@ -152,9 +152,9 @@ void HttpServerFilter::Call::OnServerTrailingMetadata(ServerMetadata& md) { FilterOutgoingMetadata(&md); } -absl::StatusOr HttpServerFilter::Create( +absl::StatusOr> HttpServerFilter::Create( const ChannelArgs& args, ChannelFilter::Args) { - return HttpServerFilter( + return std::make_unique( args.GetBool(GRPC_ARG_SURFACE_USER_AGENT).value_or(true), args.GetBool( GRPC_ARG_DO_NOT_USE_UNLESS_YOU_HAVE_PERMISSION_FROM_GRPC_TEAM_ALLOW_BROKEN_PUT_REQUESTS) diff --git a/src/core/ext/filters/http/server/http_server_filter.h b/src/core/ext/filters/http/server/http_server_filter.h index a87c83518ee..282973ddecd 100644 --- a/src/core/ext/filters/http/server/http_server_filter.h +++ b/src/core/ext/filters/http/server/http_server_filter.h @@ -36,9 +36,13 @@ class HttpServerFilter : public ImplementChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + HttpServerFilter(bool surface_user_agent, bool allow_put_requests) + : surface_user_agent_(surface_user_agent), + allow_put_requests_(allow_put_requests) {} + class Call { public: ServerMetadataHandle OnClientInitialMetadata(ClientMetadata& md, @@ -51,10 +55,6 @@ class HttpServerFilter : public ImplementChannelFilter { }; private: - HttpServerFilter(bool surface_user_agent, bool allow_put_requests) - : surface_user_agent_(surface_user_agent), - allow_put_requests_(allow_put_requests) {} - bool surface_user_agent_; bool allow_put_requests_; }; diff --git a/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc b/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc index 624ca70e79e..7937ab6fe74 100644 --- a/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc +++ b/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc @@ -76,10 +76,11 @@ const NoInterceptor ServerLoadReportingFilter::Call::OnServerInitialMetadata; const NoInterceptor ServerLoadReportingFilter::Call::OnClientToServerMessage; const NoInterceptor ServerLoadReportingFilter::Call::OnServerToClientMessage; -absl::StatusOr ServerLoadReportingFilter::Create( - const ChannelArgs& channel_args, ChannelFilter::Args) { +absl::StatusOr> +ServerLoadReportingFilter::Create(const ChannelArgs& channel_args, + ChannelFilter::Args) { // Find and record the peer_identity. - ServerLoadReportingFilter filter; + auto filter = std::make_unique(); const auto* auth_context = channel_args.GetObject(); if (auth_context != nullptr && grpc_auth_context_peer_is_authenticated(auth_context)) { @@ -88,7 +89,7 @@ absl::StatusOr ServerLoadReportingFilter::Create( const grpc_auth_property* auth_property = grpc_auth_property_iterator_next(&auth_it); if (auth_property != nullptr) { - filter.peer_identity_ = + filter->peer_identity_ = std::string(auth_property->value, auth_property->value_length); } } diff --git a/src/core/ext/filters/load_reporting/server_load_reporting_filter.h b/src/core/ext/filters/load_reporting/server_load_reporting_filter.h index ddb8d0f2482..f11c8c38bcf 100644 --- a/src/core/ext/filters/load_reporting/server_load_reporting_filter.h +++ b/src/core/ext/filters/load_reporting/server_load_reporting_filter.h @@ -39,7 +39,7 @@ class ServerLoadReportingFilter public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args); // Getters. diff --git a/src/core/ext/filters/logging/logging_filter.cc b/src/core/ext/filters/logging/logging_filter.cc index 89fe46bcb66..1c76e64b06a 100644 --- a/src/core/ext/filters/logging/logging_filter.cc +++ b/src/core/ext/filters/logging/logging_filter.cc @@ -342,21 +342,23 @@ class CallData { } // namespace -absl::StatusOr ClientLoggingFilter::Create( - const ChannelArgs& args, ChannelFilter::Args /*filter_args*/) { +absl::StatusOr> +ClientLoggingFilter::Create(const ChannelArgs& args, + ChannelFilter::Args /*filter_args*/) { absl::optional default_authority = args.GetString(GRPC_ARG_DEFAULT_AUTHORITY); if (default_authority.has_value()) { - return ClientLoggingFilter(std::string(default_authority.value())); + return std::make_unique( + std::string(default_authority.value())); } absl::optional server_uri = args.GetOwnedString(GRPC_ARG_SERVER_URI); if (server_uri.has_value()) { - return ClientLoggingFilter( + return std::make_unique( CoreConfiguration::Get().resolver_registry().GetDefaultAuthority( *server_uri)); } - return ClientLoggingFilter(""); + return std::make_unique(""); } // Construct a promise for one call. @@ -445,9 +447,10 @@ const grpc_channel_filter ClientLoggingFilter::kFilter = kFilterExaminesInboundMessages | kFilterExaminesOutboundMessages>("logging"); -absl::StatusOr ServerLoggingFilter::Create( - const ChannelArgs& /*args*/, ChannelFilter::Args /*filter_args*/) { - return ServerLoggingFilter(); +absl::StatusOr> +ServerLoggingFilter::Create(const ChannelArgs& /*args*/, + ChannelFilter::Args /*filter_args*/) { + return std::make_unique(); } // Construct a promise for one call. diff --git a/src/core/ext/filters/logging/logging_filter.h b/src/core/ext/filters/logging/logging_filter.h index 6a27a653860..7d42abbc337 100644 --- a/src/core/ext/filters/logging/logging_filter.h +++ b/src/core/ext/filters/logging/logging_filter.h @@ -39,24 +39,25 @@ class ClientLoggingFilter final : public ChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args /*filter_args*/); + explicit ClientLoggingFilter(std::string default_authority) + : default_authority_(std::move(default_authority)) {} + // Construct a promise for one call. ArenaPromise MakeCallPromise( CallArgs call_args, NextPromiseFactory next_promise_factory) override; private: - explicit ClientLoggingFilter(std::string default_authority) - : default_authority_(std::move(default_authority)) {} - std::string default_authority_; + const std::string default_authority_; }; class ServerLoggingFilter final : public ChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args /*filter_args*/); // Construct a promise for one call. diff --git a/src/core/ext/filters/message_size/message_size_filter.cc b/src/core/ext/filters/message_size/message_size_filter.cc index 252bb1a46cb..379d4944788 100644 --- a/src/core/ext/filters/message_size/message_size_filter.cc +++ b/src/core/ext/filters/message_size/message_size_filter.cc @@ -25,7 +25,6 @@ #include "absl/strings/str_format.h" -#include #include #include #include @@ -142,19 +141,20 @@ const grpc_channel_filter ClientMessageSizeFilter::kFilter = MakePromiseBasedFilter("message_size"); + const grpc_channel_filter ServerMessageSizeFilter::kFilter = MakePromiseBasedFilter("message_size"); -absl::StatusOr ClientMessageSizeFilter::Create( - const ChannelArgs& args, ChannelFilter::Args) { - return ClientMessageSizeFilter(args); +absl::StatusOr> +ClientMessageSizeFilter::Create(const ChannelArgs& args, ChannelFilter::Args) { + return std::make_unique(args); } -absl::StatusOr ServerMessageSizeFilter::Create( - const ChannelArgs& args, ChannelFilter::Args) { - return ServerMessageSizeFilter(args); +absl::StatusOr> +ServerMessageSizeFilter::Create(const ChannelArgs& args, ChannelFilter::Args) { + return std::make_unique(args); } namespace { @@ -168,7 +168,7 @@ ServerMetadataHandle CheckPayload(const Message& msg, is_send ? "send" : "recv", msg.payload()->Length(), *max_length); } if (msg.payload()->Length() <= *max_length) return nullptr; - auto r = GetContext()->MakePooled(); + auto r = Arena::MakePooled(); r->Set(GrpcStatusMetadata(), GRPC_STATUS_RESOURCE_EXHAUSTED); r->Set(GrpcMessageMetadata(), Slice::FromCopiedString(absl::StrFormat( diff --git a/src/core/ext/filters/message_size/message_size_filter.h b/src/core/ext/filters/message_size/message_size_filter.h index 3a9ea1f2064..89d21201a5c 100644 --- a/src/core/ext/filters/message_size/message_size_filter.h +++ b/src/core/ext/filters/message_size/message_size_filter.h @@ -91,9 +91,12 @@ class ServerMessageSizeFilter final public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + explicit ServerMessageSizeFilter(const ChannelArgs& args) + : parsed_config_(MessageSizeParsedConfig::GetFromChannelArgs(args)) {} + class Call { public: static const NoInterceptor OnClientInitialMetadata; @@ -107,8 +110,6 @@ class ServerMessageSizeFilter final }; private: - explicit ServerMessageSizeFilter(const ChannelArgs& args) - : parsed_config_(MessageSizeParsedConfig::GetFromChannelArgs(args)) {} const MessageSizeParsedConfig parsed_config_; }; @@ -117,9 +118,12 @@ class ClientMessageSizeFilter final public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + explicit ClientMessageSizeFilter(const ChannelArgs& args) + : parsed_config_(MessageSizeParsedConfig::GetFromChannelArgs(args)) {} + class Call { public: explicit Call(ClientMessageSizeFilter* filter); @@ -136,8 +140,6 @@ class ClientMessageSizeFilter final }; private: - explicit ClientMessageSizeFilter(const ChannelArgs& args) - : parsed_config_(MessageSizeParsedConfig::GetFromChannelArgs(args)) {} const size_t service_config_parser_index_{MessageSizeParser::ParserIndex()}; const MessageSizeParsedConfig parsed_config_; }; diff --git a/src/core/ext/filters/rbac/rbac_filter.cc b/src/core/ext/filters/rbac/rbac_filter.cc index 68c5e3d7699..7c75f46ae7d 100644 --- a/src/core/ext/filters/rbac/rbac_filter.cc +++ b/src/core/ext/filters/rbac/rbac_filter.cc @@ -82,14 +82,21 @@ RbacFilter::RbacFilter(size_t index, service_config_parser_index_(RbacServiceConfigParser::ParserIndex()), per_channel_evaluate_args_(std::move(per_channel_evaluate_args)) {} -absl::StatusOr RbacFilter::Create(const ChannelArgs& args, - ChannelFilter::Args filter_args) { +absl::StatusOr> RbacFilter::Create( + const ChannelArgs& args, ChannelFilter::Args filter_args) { auto* auth_context = args.GetObject(); if (auth_context == nullptr) { return GRPC_ERROR_CREATE("No auth context found"); } - return RbacFilter(filter_args.instance_id(), - EvaluateArgs::PerChannelArgs(auth_context, args)); + auto* transport = args.GetObject(); + if (transport == nullptr) { + // This should never happen since the transport is always set on the server + // side. + return GRPC_ERROR_CREATE("No transport configured"); + } + return std::make_unique( + filter_args.instance_id(), + EvaluateArgs::PerChannelArgs(auth_context, args)); } void RbacFilterRegister(CoreConfiguration::Builder* builder) { diff --git a/src/core/ext/filters/rbac/rbac_filter.h b/src/core/ext/filters/rbac/rbac_filter.h index f2208753b6b..a4c41cbdd0b 100644 --- a/src/core/ext/filters/rbac/rbac_filter.h +++ b/src/core/ext/filters/rbac/rbac_filter.h @@ -42,8 +42,11 @@ class RbacFilter : public ImplementChannelFilter { // and enforces the RBAC policy. static const grpc_channel_filter kFilterVtable; - static absl::StatusOr Create(const ChannelArgs& args, - ChannelFilter::Args filter_args); + static absl::StatusOr> Create( + const ChannelArgs& args, ChannelFilter::Args filter_args); + + RbacFilter(size_t index, + EvaluateArgs::PerChannelArgs per_channel_evaluate_args); class Call { public: @@ -57,9 +60,6 @@ class RbacFilter : public ImplementChannelFilter { }; private: - RbacFilter(size_t index, - EvaluateArgs::PerChannelArgs per_channel_evaluate_args); - // The index of this filter instance among instances of the same filter. size_t index_; // Assigned index for service config data from the parser. diff --git a/src/core/ext/filters/server_config_selector/server_config_selector_filter.cc b/src/core/ext/filters/server_config_selector/server_config_selector_filter.cc index 0be80a238a0..0d37c5c646c 100644 --- a/src/core/ext/filters/server_config_selector/server_config_selector_filter.cc +++ b/src/core/ext/filters/server_config_selector/server_config_selector_filter.cc @@ -49,19 +49,22 @@ namespace grpc_core { namespace { class ServerConfigSelectorFilter final - : public ImplementChannelFilter { + : public ImplementChannelFilter, + public InternallyRefCounted { public: - ~ServerConfigSelectorFilter() override; + explicit ServerConfigSelectorFilter( + RefCountedPtr + server_config_selector_provider); ServerConfigSelectorFilter(const ServerConfigSelectorFilter&) = delete; ServerConfigSelectorFilter& operator=(const ServerConfigSelectorFilter&) = delete; - ServerConfigSelectorFilter(ServerConfigSelectorFilter&&) = default; - ServerConfigSelectorFilter& operator=(ServerConfigSelectorFilter&&) = default; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args); + void Orphan() override; + class Call { public: absl::Status OnClientInitialMetadata(ClientMetadata& md, @@ -74,70 +77,66 @@ class ServerConfigSelectorFilter final }; absl::StatusOr> config_selector() { - MutexLock lock(&state_->mu); - return state_->config_selector.value(); + MutexLock lock(&mu_); + return config_selector_.value(); } private: - struct State { - Mutex mu; - absl::optional>> - config_selector ABSL_GUARDED_BY(mu); - }; class ServerConfigSelectorWatcher : public ServerConfigSelectorProvider::ServerConfigSelectorWatcher { public: - explicit ServerConfigSelectorWatcher(std::shared_ptr state) - : state_(state) {} + explicit ServerConfigSelectorWatcher( + RefCountedPtr filter) + : filter_(filter) {} void OnServerConfigSelectorUpdate( absl::StatusOr> update) override { - MutexLock lock(&state_->mu); - state_->config_selector = std::move(update); + MutexLock lock(&filter_->mu_); + filter_->config_selector_ = std::move(update); } private: - std::shared_ptr state_; + RefCountedPtr filter_; }; - explicit ServerConfigSelectorFilter( - RefCountedPtr - server_config_selector_provider); - RefCountedPtr server_config_selector_provider_; - std::shared_ptr state_; + Mutex mu_; + absl::optional>> + config_selector_ ABSL_GUARDED_BY(mu_); }; -absl::StatusOr ServerConfigSelectorFilter::Create( - const ChannelArgs& args, ChannelFilter::Args) { +absl::StatusOr> +ServerConfigSelectorFilter::Create(const ChannelArgs& args, + ChannelFilter::Args) { ServerConfigSelectorProvider* server_config_selector_provider = args.GetObject(); if (server_config_selector_provider == nullptr) { return absl::UnknownError("No ServerConfigSelectorProvider object found"); } - return ServerConfigSelectorFilter(server_config_selector_provider->Ref()); + return MakeOrphanable( + server_config_selector_provider->Ref()); } ServerConfigSelectorFilter::ServerConfigSelectorFilter( RefCountedPtr server_config_selector_provider) : server_config_selector_provider_( - std::move(server_config_selector_provider)), - state_(std::make_shared()) { + std::move(server_config_selector_provider)) { GPR_ASSERT(server_config_selector_provider_ != nullptr); auto server_config_selector_watcher = - std::make_unique(state_); + std::make_unique(Ref()); auto config_selector = server_config_selector_provider_->Watch( std::move(server_config_selector_watcher)); - MutexLock lock(&state_->mu); + MutexLock lock(&mu_); // It's possible for the watcher to have already updated config_selector_ - if (!state_->config_selector.has_value()) { - state_->config_selector = std::move(config_selector); + if (!config_selector_.has_value()) { + config_selector_ = std::move(config_selector); } } -ServerConfigSelectorFilter::~ServerConfigSelectorFilter() { +void ServerConfigSelectorFilter::Orphan() { if (server_config_selector_provider_ != nullptr) { server_config_selector_provider_->CancelWatch(); } + Unref(); } absl::Status ServerConfigSelectorFilter::Call::OnClientInitialMetadata( diff --git a/src/core/ext/filters/stateful_session/stateful_session_filter.cc b/src/core/ext/filters/stateful_session/stateful_session_filter.cc index 9345edeed7d..b64affbb61f 100644 --- a/src/core/ext/filters/stateful_session/stateful_session_filter.cc +++ b/src/core/ext/filters/stateful_session/stateful_session_filter.cc @@ -72,9 +72,10 @@ const grpc_channel_filter StatefulSessionFilter::kFilter = kFilterExaminesServerInitialMetadata>( "stateful_session_filter"); -absl::StatusOr StatefulSessionFilter::Create( - const ChannelArgs&, ChannelFilter::Args filter_args) { - return StatefulSessionFilter(filter_args); +absl::StatusOr> +StatefulSessionFilter::Create(const ChannelArgs&, + ChannelFilter::Args filter_args) { + return std::make_unique(filter_args); } StatefulSessionFilter::StatefulSessionFilter(ChannelFilter::Args filter_args) diff --git a/src/core/ext/filters/stateful_session/stateful_session_filter.h b/src/core/ext/filters/stateful_session/stateful_session_filter.h index 1fc27e1508b..5cd534843aa 100644 --- a/src/core/ext/filters/stateful_session/stateful_session_filter.h +++ b/src/core/ext/filters/stateful_session/stateful_session_filter.h @@ -74,9 +74,11 @@ class StatefulSessionFilter public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); + explicit StatefulSessionFilter(ChannelFilter::Args filter_args); + class Call { public: void OnClientInitialMetadata(ClientMetadata& md, @@ -97,7 +99,6 @@ class StatefulSessionFilter }; private: - explicit StatefulSessionFilter(ChannelFilter::Args filter_args); // The relative index of instances of the same filter. const size_t index_; // Index of the service config parser. diff --git a/src/core/ext/gcp/metadata_query.cc b/src/core/ext/gcp/metadata_query.cc index 9edbabfde49..212a7639a03 100644 --- a/src/core/ext/gcp/metadata_query.cc +++ b/src/core/ext/gcp/metadata_query.cc @@ -28,6 +28,7 @@ #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/ext/transport/binder/server/binder_server.cc b/src/core/ext/transport/binder/server/binder_server.cc index 994d8f82cb8..58d26b6949c 100644 --- a/src/core/ext/transport/binder/server/binder_server.cc +++ b/src/core/ext/transport/binder/server/binder_server.cc @@ -159,7 +159,7 @@ class BinderServerListener : public Server::ListenerInterface { on_destroy_done_ = on_destroy_done; } - void Orphan() override { delete this; } + void Orphan() override { Unref(); } ~BinderServerListener() override { ExecCtx::Get()->Flush(); @@ -239,9 +239,8 @@ bool AddBinderPort(const std::string& addr, grpc_server* server, } std::string conn_id = addr.substr(kBinderUriScheme.size()); Server* core_server = Server::FromC(server); - core_server->AddListener( - OrphanablePtr(new BinderServerListener( - core_server, conn_id, std::move(factory), security_policy))); + core_server->AddListener(MakeOrphanable( + core_server, conn_id, std::move(factory), security_policy)); return true; } diff --git a/src/core/ext/transport/chaotic_good/client_transport.cc b/src/core/ext/transport/chaotic_good/client_transport.cc index 14be491f0ee..6b3160e8182 100644 --- a/src/core/ext/transport/chaotic_good/client_transport.cc +++ b/src/core/ext/transport/chaotic_good/client_transport.cc @@ -102,14 +102,12 @@ auto ChaoticGoodClientTransport::PushFrameIntoCall(ServerFragmentFrame frame, }, []() -> StatusFlag { return Success{}; }); }, - [call_handler, trailers = std::move(frame.trailers)]() mutable { - return If( - trailers != nullptr, - [&call_handler, &trailers]() mutable { - return call_handler.PushServerTrailingMetadata( - std::move(trailers)); - }, - []() -> StatusFlag { return Success{}; }); + [call_handler, + trailers = std::move(frame.trailers)]() mutable -> StatusFlag { + if (trailers != nullptr) { + call_handler.PushServerTrailingMetadata(std::move(trailers)); + } + return Success{}; }); // Wrap the actual sequence with something that owns the call handler so that // its lifetime extends until the push completes. @@ -223,7 +221,7 @@ void ChaoticGoodClientTransport::AbortWithError() { for (const auto& pair : stream_map) { auto call_handler = pair.second; call_handler.SpawnInfallible("cancel", [call_handler]() mutable { - call_handler.Cancel(ServerMetadataFromStatus( + call_handler.PushServerTrailingMetadata(ServerMetadataFromStatus( absl::UnavailableError("Transport closed."))); return Empty{}; }); @@ -300,6 +298,10 @@ void ChaoticGoodClientTransport::StartCall(CallHandler call_handler) { const uint32_t stream_id = MakeStream(call_handler); return Map(CallOutboundLoop(stream_id, call_handler), [stream_id, this](absl::Status result) { + if (grpc_chaotic_good_trace.enabled()) { + gpr_log(GPR_INFO, "CHAOTIC_GOOD: Call %d finished with %s", + stream_id, result.ToString().c_str()); + } if (!result.ok()) { CancelFrame frame; frame.stream_id = stream_id; diff --git a/src/core/ext/transport/chaotic_good/server/chaotic_good_server.cc b/src/core/ext/transport/chaotic_good/server/chaotic_good_server.cc index c1022e95c43..f3a9de5783c 100644 --- a/src/core/ext/transport/chaotic_good/server/chaotic_good_server.cc +++ b/src/core/ext/transport/chaotic_good/server/chaotic_good_server.cc @@ -102,8 +102,8 @@ absl::StatusOr ChaoticGoodServerListener::Bind( str.ok() ? str->c_str() : str.status().ToString().c_str()); } EventEngine::Listener::AcceptCallback accept_cb = - [self = Ref()](std::unique_ptr ep, - MemoryAllocator) { + [self = RefAsSubclass()]( + std::unique_ptr ep, MemoryAllocator) { ExecCtx exec_ctx; MutexLock lock(&self->mu_); if (self->shutdown_) return; @@ -148,7 +148,8 @@ absl::Status ChaoticGoodServerListener::StartListening() { ChaoticGoodServerListener::ActiveConnection::ActiveConnection( RefCountedPtr listener, std::unique_ptr endpoint) - : memory_allocator_(listener->memory_allocator_), listener_(listener) { + : memory_allocator_(listener->memory_allocator_), + listener_(std::move(listener)) { handshaking_state_ = MakeRefCounted(Ref()); handshaking_state_->Start(std::move(endpoint)); } diff --git a/src/core/ext/transport/chaotic_good/server/chaotic_good_server.h b/src/core/ext/transport/chaotic_good/server/chaotic_good_server.h index ed90dd45d1d..a34fbee3f18 100644 --- a/src/core/ext/transport/chaotic_good/server/chaotic_good_server.h +++ b/src/core/ext/transport/chaotic_good/server/chaotic_good_server.h @@ -49,9 +49,7 @@ namespace grpc_core { namespace chaotic_good { -class ChaoticGoodServerListener final - : public Server::ListenerInterface, - public RefCounted { +class ChaoticGoodServerListener final : public Server::ListenerInterface { public: static absl::AnyInvocable DefaultConnectionIDGenerator() { return [bitgen = absl::BitGen()]() mutable { diff --git a/src/core/ext/transport/chaotic_good/server_transport.cc b/src/core/ext/transport/chaotic_good/server_transport.cc index 05edb2d0eb3..7975975203c 100644 --- a/src/core/ext/transport/chaotic_good/server_transport.cc +++ b/src/core/ext/transport/chaotic_good/server_transport.cc @@ -72,33 +72,29 @@ auto ChaoticGoodServerTransport::TransportWriteLoop( auto ChaoticGoodServerTransport::PushFragmentIntoCall( CallInitiator call_initiator, ClientFragmentFrame frame, uint32_t stream_id) { - auto& headers = frame.headers; - return TrySeq( - If( - headers != nullptr, - [call_initiator, &headers]() mutable { - return call_initiator.PushClientInitialMetadata(std::move(headers)); - }, - []() -> StatusFlag { return Success{}; }), - [call_initiator, message = std::move(frame.message)]() mutable { - return If( - message.has_value(), - [&call_initiator, &message]() mutable { - return call_initiator.PushMessage(std::move(message->message)); - }, - []() -> StatusFlag { return Success{}; }); - }, - [this, call_initiator, end_of_stream = frame.end_of_stream, - stream_id]() mutable -> StatusFlag { - if (end_of_stream) { - call_initiator.FinishSends(); - // We have received end_of_stream. It is now safe to remove the call - // from the stream map. - MutexLock lock(&mu_); - stream_map_.erase(stream_id); - } - return Success{}; - }); + GPR_DEBUG_ASSERT(frame.headers == nullptr); + if (grpc_chaotic_good_trace.enabled()) { + gpr_log(GPR_INFO, "CHAOTIC_GOOD: PushFragmentIntoCall: frame=%s", + frame.ToString().c_str()); + } + return TrySeq(If( + frame.message.has_value(), + [&call_initiator, &frame]() mutable { + return call_initiator.PushMessage( + std::move(frame.message->message)); + }, + []() -> StatusFlag { return Success{}; }), + [this, call_initiator, end_of_stream = frame.end_of_stream, + stream_id]() mutable -> StatusFlag { + if (end_of_stream) { + call_initiator.FinishSends(); + // We have received end_of_stream. It is now safe to remove + // the call from the stream map. + MutexLock lock(&mu_); + stream_map_.erase(stream_id); + } + return Success{}; + }); } auto ChaoticGoodServerTransport::MaybePushFragmentIntoCall( @@ -244,8 +240,8 @@ auto ChaoticGoodServerTransport::DeserializeAndPushFragmentToNewCall( FrameLimits{1024 * 1024 * 1024, aligned_bytes_ - 1}); absl::optional call_initiator; if (status.ok()) { - auto create_call_result = - acceptor_->CreateCall(*fragment_frame.headers, arena.release()); + auto create_call_result = acceptor_->CreateCall( + std::move(fragment_frame.headers), arena.release()); if (grpc_chaotic_good_trace.enabled()) { gpr_log(GPR_INFO, "CHAOTIC_GOOD: DeserializeAndPushFragmentToNewCall: " diff --git a/src/core/ext/transport/chttp2/server/chttp2_server.cc b/src/core/ext/transport/chttp2/server/chttp2_server.cc index 2e97b207ed2..4496189cd6a 100644 --- a/src/core/ext/transport/chttp2/server/chttp2_server.cc +++ b/src/core/ext/transport/chttp2/server/chttp2_server.cc @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -55,6 +56,8 @@ #include "src/core/lib/config/core_configuration.h" #include "src/core/lib/debug/trace.h" #include "src/core/lib/event_engine/channel_args_endpoint_config.h" +#include "src/core/lib/event_engine/extensions/supports_fd.h" +#include "src/core/lib/event_engine/query_extensions.h" #include "src/core/lib/gprpp/debug_location.h" #include "src/core/lib/gprpp/orphanable.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" @@ -64,6 +67,7 @@ #include "src/core/lib/gprpp/unique_type_name.h" #include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/endpoint.h" +#include "src/core/lib/iomgr/event_engine_shims/endpoint.h" #include "src/core/lib/iomgr/iomgr_fwd.h" #include "src/core/lib/iomgr/pollset_set.h" #include "src/core/lib/iomgr/resolve_address.h" @@ -92,9 +96,11 @@ #endif // GPR_SUPPORT_CHANNELS_FROM_FD namespace grpc_core { -namespace { -using ::grpc_event_engine::experimental::EventEngine; +using grpc_event_engine::experimental::ChannelArgsEndpointConfig; +using grpc_event_engine::experimental::EventEngine; +using grpc_event_engine::experimental::EventEngineSupportsFdExtension; +using grpc_event_engine::experimental::QueryExtension; const char kUnixUriPrefix[] = "unix:"; const char kUnixAbstractUriPrefix[] = "unix-abstract:"; @@ -111,14 +117,23 @@ class Chttp2ServerListener : public Server::ListenerInterface { Server* server, const char* name, const ChannelArgs& args, Chttp2ServerArgsModifier args_modifier); + static Chttp2ServerListener* CreateForPassiveListener( + Server* server, const ChannelArgs& args, + std::shared_ptr passive_listener); + // Do not instantiate directly. Use one of the factory methods above. Chttp2ServerListener(Server* server, const ChannelArgs& args, - Chttp2ServerArgsModifier args_modifier); + Chttp2ServerArgsModifier args_modifier, + grpc_server_config_fetcher* config_fetcher, + std::shared_ptr + passive_listener = nullptr); ~Chttp2ServerListener() override; void Start(Server* server, const std::vector* pollsets) override; + void AcceptConnectedEndpoint(std::unique_ptr endpoint); + channelz::ListenSocketNode* channelz_listen_socket_node() const override { return channelz_listen_socket_.get(); } @@ -128,6 +143,8 @@ class Chttp2ServerListener : public Server::ListenerInterface { void Orphan() override; private: + friend class experimental::PassiveListenerImpl; + class ConfigFetcherWatcher : public grpc_server_config_fetcher::WatcherInterface { public: @@ -234,34 +251,8 @@ class Chttp2ServerListener : public Server::ListenerInterface { static void DestroyListener(Server* /*server*/, void* arg, grpc_closure* destroy_done); - // The interface required by RefCountedPtr<> has been manually implemented - // here to take a ref on tcp_server_ instead. Note that, the handshaker - // needs tcp_server_ to exist for the lifetime of the handshake since it's - // needed by acceptor. Sharing refs between the listener and tcp_server_ is - // just an optimization to avoid taking additional refs on the listener, - // since TcpServerShutdownComplete already holds a ref to the listener. - void IncrementRefCount() { grpc_tcp_server_ref(tcp_server_); } - void IncrementRefCount(const DebugLocation& /* location */, - const char* /* reason */) { - IncrementRefCount(); - } - - GRPC_MUST_USE_RESULT RefCountedPtr Ref() { - IncrementRefCount(); - return RefCountedPtr(this); - } - GRPC_MUST_USE_RESULT RefCountedPtr Ref( - const DebugLocation& /* location */, const char* /* reason */) { - return Ref(); - } - - void Unref() { grpc_tcp_server_unref(tcp_server_); } - void Unref(const DebugLocation& /* location */, const char* /* reason */) { - Unref(); - } - - Server* const server_; - grpc_tcp_server* tcp_server_; + Server* const server_ = nullptr; + grpc_tcp_server* tcp_server_ = nullptr; grpc_resolved_address resolved_address_; Chttp2ServerArgsModifier const args_modifier_; ConfigFetcherWatcher* config_fetcher_watcher_ = nullptr; @@ -284,6 +275,10 @@ class Chttp2ServerListener : public Server::ListenerInterface { RefCountedPtr channelz_listen_socket_; MemoryQuotaRefPtr memory_quota_; ConnectionQuotaRefPtr connection_quota_; + grpc_server_config_fetcher* config_fetcher_ = nullptr; + // TODO(yashykt): consider using absl::variant<> to minimize memory usage for + // disjoint cases where different fields are used. + std::shared_ptr passive_listener_; }; // @@ -380,13 +375,17 @@ Chttp2ServerListener::ActiveConnection::HandshakingState::HandshakingState( handshake_mgr_(MakeRefCounted()), deadline_(GetConnectionDeadline(args)), interested_parties_(grpc_pollset_set_create()) { - grpc_pollset_set_add_pollset(interested_parties_, accepting_pollset_); + if (accepting_pollset != nullptr) { + grpc_pollset_set_add_pollset(interested_parties_, accepting_pollset_); + } CoreConfiguration::Get().handshaker_registry().AddHandshakers( HANDSHAKER_SERVER, args, interested_parties_, handshake_mgr_.get()); } Chttp2ServerListener::ActiveConnection::HandshakingState::~HandshakingState() { - grpc_pollset_set_del_pollset(interested_parties_, accepting_pollset_); + if (accepting_pollset_ != nullptr) { + grpc_pollset_set_del_pollset(interested_parties_, accepting_pollset_); + } grpc_pollset_set_destroy(interested_parties_); gpr_free(acceptor_); } @@ -708,83 +707,82 @@ void Chttp2ServerListener::ActiveConnection::OnDrainGraceTimeExpiry() { grpc_error_handle Chttp2ServerListener::Create( Server* server, grpc_resolved_address* addr, const ChannelArgs& args, Chttp2ServerArgsModifier args_modifier, int* port_num) { - Chttp2ServerListener* listener = nullptr; - // The bulk of this method is inside of a lambda to make cleanup - // easier without using goto. - grpc_error_handle error = [&]() { - grpc_error_handle error; - // Create Chttp2ServerListener. - listener = new Chttp2ServerListener(server, args, args_modifier); - error = grpc_tcp_server_create( - &listener->tcp_server_shutdown_complete_, - grpc_event_engine::experimental::ChannelArgsEndpointConfig(args), - OnAccept, listener, &listener->tcp_server_); + // Create Chttp2ServerListener. + OrphanablePtr listener = + MakeOrphanable(server, args, args_modifier, + server->config_fetcher()); + // The tcp_server will be unreffed when the listener is orphaned, which could + // be at the end of this function if the listener was not added to the + // server's set of listeners. + grpc_error_handle error = grpc_tcp_server_create( + &listener->tcp_server_shutdown_complete_, ChannelArgsEndpointConfig(args), + OnAccept, listener.get(), &listener->tcp_server_); + if (!error.ok()) return error; + if (listener->config_fetcher_ != nullptr) { + listener->resolved_address_ = *addr; + // TODO(yashykt): Consider binding so as to be able to return the port + // number. + } else { + error = grpc_tcp_server_add_port(listener->tcp_server_, addr, port_num); if (!error.ok()) return error; - if (server->config_fetcher() != nullptr) { - listener->resolved_address_ = *addr; - // TODO(yashykt): Consider binding so as to be able to return the port - // number. - } else { - error = grpc_tcp_server_add_port(listener->tcp_server_, addr, port_num); - if (!error.ok()) return error; - } - // Create channelz node. - if (args.GetBool(GRPC_ARG_ENABLE_CHANNELZ) - .value_or(GRPC_ENABLE_CHANNELZ_DEFAULT)) { - auto string_address = grpc_sockaddr_to_uri(addr); - if (!string_address.ok()) { - return GRPC_ERROR_CREATE(string_address.status().ToString()); - } - listener->channelz_listen_socket_ = - MakeRefCounted( - *string_address, - absl::StrCat("chttp2 listener ", *string_address)); - } - // Register with the server only upon success - server->AddListener(OrphanablePtr(listener)); - return absl::OkStatus(); - }(); - if (!error.ok()) { - if (listener != nullptr) { - if (listener->tcp_server_ != nullptr) { - // listener is deleted when tcp_server_ is shutdown. - grpc_tcp_server_unref(listener->tcp_server_); - } else { - delete listener; - } + } + // Create channelz node. + if (args.GetBool(GRPC_ARG_ENABLE_CHANNELZ) + .value_or(GRPC_ENABLE_CHANNELZ_DEFAULT)) { + auto string_address = grpc_sockaddr_to_uri(addr); + if (!string_address.ok()) { + return GRPC_ERROR_CREATE(string_address.status().ToString()); } + listener->channelz_listen_socket_ = + MakeRefCounted( + *string_address, absl::StrCat("chttp2 listener ", *string_address)); } - return error; + // Register with the server only upon success + server->AddListener(std::move(listener)); + return absl::OkStatus(); } grpc_error_handle Chttp2ServerListener::CreateWithAcceptor( Server* server, const char* name, const ChannelArgs& args, Chttp2ServerArgsModifier args_modifier) { - Chttp2ServerListener* listener = - new Chttp2ServerListener(server, args, args_modifier); + auto listener = MakeOrphanable( + server, args, args_modifier, server->config_fetcher()); grpc_error_handle error = grpc_tcp_server_create( - &listener->tcp_server_shutdown_complete_, - grpc_event_engine::experimental::ChannelArgsEndpointConfig(args), - OnAccept, listener, &listener->tcp_server_); - if (!error.ok()) { - delete listener; - return error; - } + &listener->tcp_server_shutdown_complete_, ChannelArgsEndpointConfig(args), + OnAccept, listener.get(), &listener->tcp_server_); + if (!error.ok()) return error; // TODO(yangg) channelz TcpServerFdHandler** arg_val = args.GetPointer(name); *arg_val = grpc_tcp_server_create_fd_handler(listener->tcp_server_); - server->AddListener(OrphanablePtr(listener)); + server->AddListener(std::move(listener)); return absl::OkStatus(); } +Chttp2ServerListener* Chttp2ServerListener::CreateForPassiveListener( + Server* server, const ChannelArgs& args, + std::shared_ptr passive_listener) { + // TODO(hork): figure out how to handle channelz in this case + auto listener = MakeOrphanable( + server, args, /*args_modifier=*/ + [](const ChannelArgs& args, grpc_error_handle*) { return args; }, nullptr, + std::move(passive_listener)); + auto listener_ptr = listener.get(); + server->AddListener(std::move(listener)); + return listener_ptr; +} + Chttp2ServerListener::Chttp2ServerListener( Server* server, const ChannelArgs& args, - Chttp2ServerArgsModifier args_modifier) + Chttp2ServerArgsModifier args_modifier, + grpc_server_config_fetcher* config_fetcher, + std::shared_ptr passive_listener) : server_(server), args_modifier_(args_modifier), args_(args), memory_quota_(args.GetObject()->memory_quota()), - connection_quota_(MakeRefCounted()) { + connection_quota_(MakeRefCounted()), + config_fetcher_(config_fetcher), + passive_listener_(std::move(passive_listener)) { auto max_allowed_incoming_connections = args.GetInt(GRPC_ARG_MAX_ALLOWED_INCOMING_CONNECTIONS); if (max_allowed_incoming_connections.has_value()) { @@ -799,6 +797,9 @@ Chttp2ServerListener::~Chttp2ServerListener() { // Flush queued work before destroying handshaker factory, since that // may do a synchronous unref. ExecCtx::Get()->Flush(); + if (passive_listener_ != nullptr) { + passive_listener_->ListenerDestroyed(); + } if (on_destroy_done_ != nullptr) { ExecCtx::Run(DEBUG_LOCATION, on_destroy_done_, absl::OkStatus()); ExecCtx::Get()->Flush(); @@ -808,10 +809,11 @@ Chttp2ServerListener::~Chttp2ServerListener() { // Server callback: start listening on our ports void Chttp2ServerListener::Start( Server* /*server*/, const std::vector* /* pollsets */) { - if (server_->config_fetcher() != nullptr) { - auto watcher = std::make_unique(Ref()); + if (config_fetcher_ != nullptr) { + auto watcher = std::make_unique( + RefAsSubclass()); config_fetcher_watcher_ = watcher.get(); - server_->config_fetcher()->StartWatch( + config_fetcher_->StartWatch( grpc_sockaddr_to_string(&resolved_address_, false).value(), std::move(watcher)); } else { @@ -825,7 +827,9 @@ void Chttp2ServerListener::Start( } void Chttp2ServerListener::StartListening() { - grpc_tcp_server_start(tcp_server_, &server_->pollsets()); + if (tcp_server_ != nullptr) { + grpc_tcp_server_start(tcp_server_, &server_->pollsets()); + } } void Chttp2ServerListener::SetOnDestroyDone(grpc_closure* on_destroy_done) { @@ -833,6 +837,12 @@ void Chttp2ServerListener::SetOnDestroyDone(grpc_closure* on_destroy_done) { on_destroy_done_ = on_destroy_done; } +void Chttp2ServerListener::AcceptConnectedEndpoint( + std::unique_ptr endpoint) { + OnAccept(this, grpc_event_engine_endpoint_create(std::move(endpoint)), + /*accepting_pollset=*/nullptr, /*acceptor=*/nullptr); +} + void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp, grpc_pollset* accepting_pollset, grpc_tcp_server_acceptor* acceptor) { @@ -857,7 +867,7 @@ void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp, endpoint_cleanup(error); return; } - if (self->server_->config_fetcher() != nullptr) { + if (self->config_fetcher_ != nullptr) { if (connection_manager == nullptr) { grpc_error_handle error = GRPC_ERROR_CREATE( "No ConnectionManager configured. Closing connection."); @@ -898,7 +908,7 @@ void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp, // heap-use-after-free issues where `Ref()` is invoked when the ref of // tcp_server_ has already reached 0. (Ref() implementation of // Chttp2ServerListener is grpc_tcp_server_ref().) - listener_ref = self->Ref(); + listener_ref = self->RefAsSubclass(); self->connections_.emplace(connection.get(), std::move(connection)); } } @@ -913,7 +923,7 @@ void Chttp2ServerListener::TcpServerShutdownComplete( void* arg, grpc_error_handle /*error*/) { Chttp2ServerListener* self = static_cast(arg); self->channelz_listen_socket_.reset(); - delete self; + self->Unref(); } // Server callback: destroy the tcp listener (so we don't generate further @@ -922,7 +932,8 @@ void Chttp2ServerListener::Orphan() { // Cancel the watch before shutting down so as to avoid holding a ref to the // listener in the watcher. if (config_fetcher_watcher_ != nullptr) { - server_->config_fetcher()->CancelWatch(config_fetcher_watcher_); + GPR_ASSERT(config_fetcher_ != nullptr); + config_fetcher_->CancelWatch(config_fetcher_watcher_); } std::map> connections; grpc_tcp_server* tcp_server; @@ -940,12 +951,14 @@ void Chttp2ServerListener::Orphan() { } tcp_server = tcp_server_; } - grpc_tcp_server_shutdown_listeners(tcp_server); - grpc_tcp_server_unref(tcp_server); + if (tcp_server != nullptr) { + grpc_tcp_server_shutdown_listeners(tcp_server); + grpc_tcp_server_unref(tcp_server); + } else { + Unref(); + } } -} // namespace - // // Chttp2ServerAddPort() // @@ -1046,6 +1059,50 @@ ChannelArgs ModifyArgsForConnection(const ChannelArgs& args, } } // namespace + +namespace experimental { + +absl::Status PassiveListenerImpl::AcceptConnectedEndpoint( + std::unique_ptr endpoint) { + GPR_ASSERT(server_ != nullptr); + RefCountedPtr listener; + { + MutexLock lock(&mu_); + if (listener_ != nullptr) { + listener = + listener_->RefIfNonZero().TakeAsSubclass(); + } + } + if (listener == nullptr) { + return absl::UnavailableError("passive listener already shut down"); + } + ExecCtx exec_ctx; + listener->AcceptConnectedEndpoint(std::move(endpoint)); + return absl::OkStatus(); +} + +absl::Status PassiveListenerImpl::AcceptConnectedFd(int fd) { + GPR_ASSERT(server_ != nullptr); + ExecCtx exec_ctx; + auto& args = server_->channel_args(); + auto* supports_fd = QueryExtension( + /*engine=*/args.GetObjectRef().get()); + if (supports_fd == nullptr) { + return absl::UnimplementedError( + "The server's EventEngine does not support adding endpoints from " + "connected file descriptors."); + } + auto endpoint = + supports_fd->CreateEndpointFromFd(fd, ChannelArgsEndpointConfig(args)); + return AcceptConnectedEndpoint(std::move(endpoint)); +} + +void PassiveListenerImpl::ListenerDestroyed() { + MutexLock lock(&mu_); + listener_ = nullptr; +} + +} // namespace experimental } // namespace grpc_core int grpc_server_add_http2_port(grpc_server* server, const char* addr, @@ -1143,3 +1200,31 @@ void grpc_server_add_channel_from_fd(grpc_server* /* server */, int /* fd */, } #endif // GPR_SUPPORT_CHANNELS_FROM_FD + +absl::Status grpc_server_add_passive_listener( + grpc_core::Server* server, grpc_server_credentials* credentials, + std::shared_ptr + passive_listener) { + grpc_core::ExecCtx exec_ctx; + GRPC_API_TRACE("grpc_server_add_passive_listener(server=%p, credentials=%p)", + 2, (server, credentials)); + // Create security context. + if (credentials == nullptr) { + return absl::UnavailableError( + "No credentials specified for passive listener"); + } + auto sc = credentials->create_security_connector(grpc_core::ChannelArgs()); + if (sc == nullptr) { + return absl::UnavailableError( + absl::StrCat("Unable to create secure server with credentials of type ", + credentials->type().name())); + } + auto args = server->channel_args() + .SetObject(credentials->Ref()) + .SetObject(std::move(sc)); + passive_listener->listener_ = + grpc_core::Chttp2ServerListener::CreateForPassiveListener( + server, args, passive_listener); + passive_listener->server_ = server->Ref(); + return absl::OkStatus(); +} diff --git a/src/core/ext/transport/chttp2/server/chttp2_server.h b/src/core/ext/transport/chttp2/server/chttp2_server.h index f7eb7a23c66..0e296873b3d 100644 --- a/src/core/ext/transport/chttp2/server/chttp2_server.h +++ b/src/core/ext/transport/chttp2/server/chttp2_server.h @@ -21,6 +21,7 @@ #include +#include #include #include "src/core/lib/channel/channel_args.h" @@ -42,6 +43,38 @@ grpc_error_handle Chttp2ServerAddPort( Server* server, const char* addr, const ChannelArgs& args, Chttp2ServerArgsModifier connection_args_modifier, int* port_num); +class Chttp2ServerListener; +namespace experimental { + +// An implementation of the public C++ passive listener interface. +// The server builder holds a weak_ptr to one of these objects, and the +// application owns the instance. +class PassiveListenerImpl final : public PassiveListener { + public: + absl::Status AcceptConnectedEndpoint( + std::unique_ptr + endpoint) override ABSL_LOCKS_EXCLUDED(mu_); + + absl::Status AcceptConnectedFd(GRPC_UNUSED int fd) override + ABSL_LOCKS_EXCLUDED(mu_); + + void ListenerDestroyed() ABSL_LOCKS_EXCLUDED(mu_); + + private: + // note: the grpc_core::Server redundant namespace qualification is + // required for older gcc versions. + friend absl::Status(::grpc_server_add_passive_listener)( + grpc_core::Server* server, grpc_server_credentials* credentials, + std::shared_ptr + passive_listener); + + Mutex mu_; + // Data members will be populated when initialized. + RefCountedPtr server_; + Chttp2ServerListener* listener_; +}; + +} // namespace experimental } // namespace grpc_core #endif // GRPC_SRC_CORE_EXT_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H diff --git a/src/core/ext/transport/chttp2/transport/chttp2_transport.cc b/src/core/ext/transport/chttp2/transport/chttp2_transport.cc index 6be0152cae6..a1e490e44b6 100644 --- a/src/core/ext/transport/chttp2/transport/chttp2_transport.cc +++ b/src/core/ext/transport/chttp2/transport/chttp2_transport.cc @@ -1471,9 +1471,11 @@ static void perform_stream_op_locked(void* stream_op, frame_hdr[3] = static_cast(len >> 8); frame_hdr[4] = static_cast(len); - s->stats.outgoing.framing_bytes += GRPC_HEADER_SIZE_IN_BYTES; - s->stats.outgoing.data_bytes += - op_payload->send_message.send_message->Length(); + if (grpc_core::IsHttp2StatsFixEnabled()) { + s->stats.outgoing.framing_bytes += GRPC_HEADER_SIZE_IN_BYTES; + s->stats.outgoing.data_bytes += + op_payload->send_message.send_message->Length(); + } s->next_message_end_offset = s->flow_controlled_bytes_written + static_cast(s->flow_controlled_buffer.length) + diff --git a/src/core/ext/transport/chttp2/transport/frame_data.cc b/src/core/ext/transport/chttp2/transport/frame_data.cc index 334eff52f22..e10dea34134 100644 --- a/src/core/ext/transport/chttp2/transport/frame_data.cc +++ b/src/core/ext/transport/chttp2/transport/frame_data.cc @@ -78,6 +78,9 @@ void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf, grpc_slice_buffer_move_first_no_ref(inbuf, write_bytes, outbuf); stats->framing_bytes += header_size; + if (!grpc_core::IsHttp2StatsFixEnabled()) { + stats->data_bytes += write_bytes; + } } grpc_core::Poll grpc_deframe_unprocessed_incoming_frames( diff --git a/src/core/ext/transport/inproc/inproc_transport.cc b/src/core/ext/transport/inproc/inproc_transport.cc index 7be425993e1..d49dce8daf6 100644 --- a/src/core/ext/transport/inproc/inproc_transport.cc +++ b/src/core/ext/transport/inproc/inproc_transport.cc @@ -83,7 +83,7 @@ class InprocServerTransport final : public RefCounted, "inproc transport disconnected"); } - absl::StatusOr AcceptCall(ClientMetadata& md) { + absl::StatusOr AcceptCall(ClientMetadataHandle md) { switch (state_.load(std::memory_order_acquire)) { case ConnectionState::kInitial: return absl::InternalError( @@ -93,7 +93,7 @@ class InprocServerTransport final : public RefCounted, case ConnectionState::kReady: break; } - return acceptor_->CreateCall(md, acceptor_->CreateArena()); + return acceptor_->CreateCall(std::move(md), acceptor_->CreateArena()); } private: @@ -116,10 +116,10 @@ class InprocClientTransport final : public Transport, public ClientTransport { TrySeq(call_handler.PullClientInitialMetadata(), [server_transport = server_transport_, call_handler](ClientMetadataHandle md) { - auto call_initiator = server_transport->AcceptCall(*md); + auto call_initiator = + server_transport->AcceptCall(std::move(md)); if (!call_initiator.ok()) return call_initiator.status(); - ForwardCall(call_handler, std::move(*call_initiator), - std::move(md)); + ForwardCall(call_handler, std::move(*call_initiator)); return absl::OkStatus(); })); } diff --git a/src/core/ext/xds/xds_server_config_fetcher.cc b/src/core/ext/xds/xds_server_config_fetcher.cc index 75f4e704aba..a236fd05d75 100644 --- a/src/core/ext/xds/xds_server_config_fetcher.cc +++ b/src/core/ext/xds/xds_server_config_fetcher.cc @@ -38,6 +38,7 @@ #include "absl/types/optional.h" #include "absl/types/variant.h" +#include #include #include #include diff --git a/src/core/lib/channel/channel_stack_builder_impl.cc b/src/core/lib/channel/channel_stack_builder_impl.cc index 6fd0b9f6484..62c527ffe61 100644 --- a/src/core/lib/channel/channel_stack_builder_impl.cc +++ b/src/core/lib/channel/channel_stack_builder_impl.cc @@ -95,43 +95,37 @@ const grpc_channel_filter* PromiseTracingFilterFor( }, /* init_call: */ [](grpc_channel_element* elem, CallSpineInterface* call) { + auto* c = DownCast(call); auto* source_filter = static_cast(elem->filter)->filter; - call->client_initial_metadata().receiver.InterceptAndMap( + c->client_initial_metadata().receiver.InterceptAndMap( [source_filter](ClientMetadataHandle md) { gpr_log(GPR_DEBUG, "%s[%s] OnClientInitialMetadata: %s", GetContext()->DebugTag().c_str(), source_filter->name, md->DebugString().c_str()); return md; }); - call->client_to_server_messages().receiver.InterceptAndMap( + c->client_to_server_messages().receiver.InterceptAndMap( [source_filter](MessageHandle msg) { gpr_log(GPR_DEBUG, "%s[%s] OnClientToServerMessage: %s", GetContext()->DebugTag().c_str(), source_filter->name, msg->DebugString().c_str()); return msg; }); - call->server_initial_metadata().sender.InterceptAndMap( + c->server_initial_metadata().sender.InterceptAndMap( [source_filter](ServerMetadataHandle md) { gpr_log(GPR_DEBUG, "%s[%s] OnServerInitialMetadata: %s", GetContext()->DebugTag().c_str(), source_filter->name, md->DebugString().c_str()); return md; }); - call->server_to_client_messages().sender.InterceptAndMap( + c->server_to_client_messages().sender.InterceptAndMap( [source_filter](MessageHandle msg) { gpr_log(GPR_DEBUG, "%s[%s] OnServerToClientMessage: %s", GetContext()->DebugTag().c_str(), source_filter->name, msg->DebugString().c_str()); return msg; }); - call->server_trailing_metadata().sender.InterceptAndMap( - [source_filter](ServerMetadataHandle md) { - gpr_log(GPR_DEBUG, "%s[%s] OnServerTrailingMetadata: %s", - GetContext()->DebugTag().c_str(), - source_filter->name, md->DebugString().c_str()); - return md; - }); }, grpc_channel_next_op, /* sizeof_call_data: */ 0, diff --git a/src/core/lib/channel/connected_channel.cc b/src/core/lib/channel/connected_channel.cc index f54e64c1aa7..6cbf9df086e 100644 --- a/src/core/lib/channel/connected_channel.cc +++ b/src/core/lib/channel/connected_channel.cc @@ -463,8 +463,7 @@ ArenaPromise MakeClientCallPromise(Transport* transport, [](absl::Status) {}); // Start a promise to receive server initial metadata and then forward it up // through the receiving pipe. - auto server_initial_metadata = - GetContext()->MakePooled(); + auto server_initial_metadata = Arena::MakePooled(); party->Spawn( "recv_initial_metadata", TrySeq(GetContext()->ReceiveServerInitialMetadata( @@ -501,27 +500,25 @@ ArenaPromise MakeClientCallPromise(Transport* transport, // Create a promise that will receive server trailing metadata. // If this fails, we massage the error into metadata that we can report // upwards. - auto server_trailing_metadata = - GetContext()->MakePooled(); - auto recv_trailing_metadata = - Map(GetContext()->ReceiveServerTrailingMetadata( - stream->batch_target()), - [](absl::StatusOr status) mutable { - if (!status.ok()) { - auto server_trailing_metadata = - GetContext()->MakePooled(); - grpc_status_code status_code = GRPC_STATUS_UNKNOWN; - std::string message; - grpc_error_get_status(status.status(), Timestamp::InfFuture(), - &status_code, &message, nullptr, nullptr); - server_trailing_metadata->Set(GrpcStatusMetadata(), status_code); - server_trailing_metadata->Set(GrpcMessageMetadata(), - Slice::FromCopiedString(message)); - return server_trailing_metadata; - } else { - return std::move(*status); - } - }); + auto server_trailing_metadata = Arena::MakePooled(); + auto recv_trailing_metadata = Map( + GetContext()->ReceiveServerTrailingMetadata( + stream->batch_target()), + [](absl::StatusOr status) mutable { + if (!status.ok()) { + auto server_trailing_metadata = Arena::MakePooled(); + grpc_status_code status_code = GRPC_STATUS_UNKNOWN; + std::string message; + grpc_error_get_status(status.status(), Timestamp::InfFuture(), + &status_code, &message, nullptr, nullptr); + server_trailing_metadata->Set(GrpcStatusMetadata(), status_code); + server_trailing_metadata->Set(GrpcMessageMetadata(), + Slice::FromCopiedString(message)); + return server_trailing_metadata; + } else { + return std::move(*status); + } + }); // Finally the main call promise. // Concurrently: send initial metadata and receive messages, until BOTH // complete (or one fails). @@ -784,8 +781,7 @@ ArenaPromise MakeServerCallPromise( if (status.ok()) { trailing_metadata = std::move(*status); } else { - trailing_metadata = - GetContext()->MakePooled(); + trailing_metadata = Arena::MakePooled(); grpc_status_code status_code = GRPC_STATUS_UNKNOWN; std::string message; grpc_error_get_status(status.status(), Timestamp::InfFuture(), @@ -888,18 +884,7 @@ ArenaPromise MakeClientTransportCallPromise( Transport* transport, CallArgs call_args, NextPromiseFactory) { auto spine = GetContext()->MakeCallSpine(std::move(call_args)); transport->client_transport()->StartCall(CallHandler{spine}); - return Map(spine->server_trailing_metadata().receiver.Next(), - [](NextResult r) { - if (r.has_value()) { - auto md = std::move(r.value()); - md->Set(GrpcStatusFromWire(), true); - return md; - } - auto m = GetContext()->MakePooled(); - m->Set(GrpcStatusMetadata(), GRPC_STATUS_CANCELLED); - m->Set(GrpcCallWasCancelled(), true); - return m; - }); + return spine->PullServerTrailingMetadata(); } const grpc_channel_filter kClientPromiseBasedTransportFilter = diff --git a/src/core/lib/channel/promise_based_filter.cc b/src/core/lib/channel/promise_based_filter.cc index e5fe93ab058..9e47aacae55 100644 --- a/src/core/lib/channel/promise_based_filter.cc +++ b/src/core/lib/channel/promise_based_filter.cc @@ -106,7 +106,7 @@ BaseCallData::BaseCallData( ? arena_->New(this, make_recv_interceptor()) : nullptr), event_engine_( - static_cast(elem->channel_data) + ChannelFilterFromElem(elem) ->hack_until_per_channel_stack_event_engines_land_get_event_engine()) { } @@ -508,7 +508,7 @@ void BaseCallData::SendMessage::WakeInsideCombiner(Flusher* flusher, case State::kGotBatch: if (allow_push_to_pipe) { state_ = State::kPushedToPipe; - auto message = GetContext()->MakePooled(); + auto message = Arena::MakePooled(); message->payload()->Swap(batch_->payload->send_message.send_message); message->mutable_flags() = batch_->payload->send_message.flags; push_ = interceptor()->Push()->Push(std::move(message)); @@ -839,7 +839,7 @@ void BaseCallData::ReceiveMessage::WakeInsideCombiner(Flusher* flusher, } else { state_ = State::kCompletedWhilePushedToPipe; } - auto message = GetContext()->MakePooled(); + auto message = Arena::MakePooled(); message->payload()->Swap(&**intercepted_slice_buffer_); message->mutable_flags() = *intercepted_flags_; push_ = interceptor()->Push()->Push(std::move(message)); @@ -1572,7 +1572,7 @@ void ClientCallData::Cancel(grpc_error_handle error, Flusher* flusher) { // metadata and return some trailing metadata. void ClientCallData::StartPromise(Flusher* flusher) { GPR_ASSERT(send_initial_state_ == SendInitialState::kQueued); - ChannelFilter* filter = static_cast(elem()->channel_data); + ChannelFilter* filter = promise_filter_detail::ChannelFilterFromElem(elem()); // Construct the promise. PollContext ctx(this, flusher); @@ -2369,7 +2369,7 @@ void ServerCallData::RecvInitialMetadataReady(grpc_error_handle error) { // Start the promise. ScopedContext context(this); // Construct the promise. - ChannelFilter* filter = static_cast(elem()->channel_data); + ChannelFilter* filter = promise_filter_detail::ChannelFilterFromElem(elem()); FakeActivity(this).Run([this, filter] { promise_ = filter->MakeCallPromise( CallArgs{WrapMetadata(recv_initial_metadata_), diff --git a/src/core/lib/channel/promise_based_filter.h b/src/core/lib/channel/promise_based_filter.h index 25229d16376..491cbe9c144 100644 --- a/src/core/lib/channel/promise_based_filter.h +++ b/src/core/lib/channel/promise_based_filter.h @@ -534,13 +534,14 @@ inline void InterceptClientToServerMessage(const NoInterceptor*, void*, void*, template inline void InterceptClientToServerMessage( ServerMetadataHandle (Derived::Call::*fn)(const Message&), - typename Derived::Call* call, Derived*, CallSpineInterface* call_spine) { + typename Derived::Call* call, Derived*, PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientToServerMessage); call_spine->client_to_server_messages().receiver.InterceptAndMap( [call, call_spine](MessageHandle msg) -> absl::optional { auto return_md = call->OnClientToServerMessage(*msg); if (return_md == nullptr) return std::move(msg); - return call_spine->Cancel(std::move(return_md)); + call_spine->PushServerTrailingMetadata(std::move(return_md)); + return absl::nullopt; }); } @@ -548,14 +549,15 @@ template inline void InterceptClientToServerMessage( ServerMetadataHandle (Derived::Call::*fn)(const Message&, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientToServerMessage); call_spine->client_to_server_messages().receiver.InterceptAndMap( [call, call_spine, channel](MessageHandle msg) -> absl::optional { auto return_md = call->OnClientToServerMessage(*msg, channel); if (return_md == nullptr) return std::move(msg); - return call_spine->Cancel(std::move(return_md)); + call_spine->PushServerTrailingMetadata(std::move(return_md)); + return absl::nullopt; }); } @@ -563,7 +565,7 @@ template inline void InterceptClientToServerMessage( MessageHandle (Derived::Call::*fn)(MessageHandle, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientToServerMessage); call_spine->client_to_server_messages().receiver.InterceptAndMap( [call, channel](MessageHandle msg) { @@ -575,24 +577,26 @@ template inline void InterceptClientToServerMessage( absl::StatusOr (Derived::Call::*fn)(MessageHandle, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientToServerMessage); call_spine->client_to_server_messages().receiver.InterceptAndMap( [call, call_spine, channel](MessageHandle msg) -> absl::optional { auto r = call->OnClientToServerMessage(std::move(msg), channel); if (r.ok()) return std::move(*r); - return call_spine->Cancel(ServerMetadataFromStatus(r.status())); + call_spine->PushServerTrailingMetadata( + ServerMetadataFromStatus(r.status())); + return absl::nullopt; }); } inline void InterceptClientInitialMetadata(const NoInterceptor*, void*, void*, - CallSpineInterface*) {} + PipeBasedCallSpine*) {} template inline void InterceptClientInitialMetadata( void (Derived::Call::*fn)(ClientMetadata& md), typename Derived::Call* call, - Derived*, CallSpineInterface* call_spine) { + Derived*, PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientInitialMetadata); call_spine->client_initial_metadata().receiver.InterceptAndMap( [call](ClientMetadataHandle md) { @@ -605,7 +609,7 @@ template inline void InterceptClientInitialMetadata( void (Derived::Call::*fn)(ClientMetadata& md, Derived* channel), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientInitialMetadata); call_spine->client_initial_metadata().receiver.InterceptAndMap( [call, channel](ClientMetadataHandle md) { @@ -617,14 +621,15 @@ inline void InterceptClientInitialMetadata( template inline void InterceptClientInitialMetadata( ServerMetadataHandle (Derived::Call::*fn)(ClientMetadata& md), - typename Derived::Call* call, Derived*, CallSpineInterface* call_spine) { + typename Derived::Call* call, Derived*, PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientInitialMetadata); call_spine->client_initial_metadata().receiver.InterceptAndMap( [call_spine, call](ClientMetadataHandle md) -> absl::optional { auto return_md = call->OnClientInitialMetadata(*md); if (return_md == nullptr) return std::move(md); - return call_spine->Cancel(std::move(return_md)); + call_spine->PushServerTrailingMetadata(std::move(return_md)); + return absl::nullopt; }); } @@ -633,28 +638,31 @@ inline void InterceptClientInitialMetadata( ServerMetadataHandle (Derived::Call::*fn)(ClientMetadata& md, Derived* channel), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientInitialMetadata); call_spine->client_initial_metadata().receiver.InterceptAndMap( [call_spine, call, channel]( ClientMetadataHandle md) -> absl::optional { auto return_md = call->OnClientInitialMetadata(*md, channel); if (return_md == nullptr) return std::move(md); - return call_spine->Cancel(std::move(return_md)); + call_spine->PushServerTrailingMetadata(std::move(return_md)); + return absl::nullopt; }); } template inline void InterceptClientInitialMetadata( absl::Status (Derived::Call::*fn)(ClientMetadata& md), - typename Derived::Call* call, Derived*, CallSpineInterface* call_spine) { + typename Derived::Call* call, Derived*, PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientInitialMetadata); call_spine->client_initial_metadata().receiver.InterceptAndMap( [call_spine, call](ClientMetadataHandle md) -> absl::optional { auto status = call->OnClientInitialMetadata(*md); if (status.ok()) return std::move(md); - return call_spine->Cancel(ServerMetadataFromStatus(status)); + call_spine->PushServerTrailingMetadata( + ServerMetadataFromStatus(status)); + return absl::nullopt; }); } @@ -662,14 +670,16 @@ template inline void InterceptClientInitialMetadata( absl::Status (Derived::Call::*fn)(ClientMetadata& md, Derived* channel), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnClientInitialMetadata); call_spine->client_initial_metadata().receiver.InterceptAndMap( [call_spine, call, channel]( ClientMetadataHandle md) -> absl::optional { auto status = call->OnClientInitialMetadata(*md, channel); if (status.ok()) return std::move(md); - return call_spine->Cancel(ServerMetadataFromStatus(status)); + call_spine->PushServerTrailingMetadata( + ServerMetadataFromStatus(status)); + return absl::nullopt; }); } @@ -681,7 +691,7 @@ absl::void_t( InterceptClientInitialMetadata(Promise (Derived::Call::*promise_factory)( ClientMetadata& md, Derived* channel), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(promise_factory == &Derived::Call::OnClientInitialMetadata); call_spine->client_initial_metadata().receiver.InterceptAndMap( [call, call_spine, channel](ClientMetadataHandle md) { @@ -691,8 +701,9 @@ InterceptClientInitialMetadata(Promise (Derived::Call::*promise_factory)( call_spine](PromiseResult status) mutable -> absl::optional { if (IsStatusOk(status)) return std::move(md); - return call_spine->Cancel( + call_spine->PushServerTrailingMetadata( StatusCast(std::move(status))); + return absl::nullopt; }); }); } @@ -766,7 +777,7 @@ inline void InterceptServerInitialMetadata(const NoInterceptor*, void*, void*, template inline void InterceptServerInitialMetadata( void (Derived::Call::*fn)(ServerMetadata&), typename Derived::Call* call, - Derived*, CallSpineInterface* call_spine) { + Derived*, PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerInitialMetadata); call_spine->server_initial_metadata().sender.InterceptAndMap( [call](ServerMetadataHandle md) { @@ -778,14 +789,16 @@ inline void InterceptServerInitialMetadata( template inline void InterceptServerInitialMetadata( absl::Status (Derived::Call::*fn)(ServerMetadata&), - typename Derived::Call* call, Derived*, CallSpineInterface* call_spine) { + typename Derived::Call* call, Derived*, PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerInitialMetadata); call_spine->server_initial_metadata().sender.InterceptAndMap( [call, call_spine]( ServerMetadataHandle md) -> absl::optional { auto status = call->OnServerInitialMetadata(*md); if (status.ok()) return std::move(md); - return call_spine->Cancel(ServerMetadataFromStatus(status)); + call_spine->PushServerTrailingMetadata( + ServerMetadataFromStatus(status)); + return absl::nullopt; }); } @@ -793,7 +806,7 @@ template inline void InterceptServerInitialMetadata( void (Derived::Call::*fn)(ServerMetadata&, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerInitialMetadata); call_spine->server_initial_metadata().sender.InterceptAndMap( [call, channel](ServerMetadataHandle md) { @@ -806,14 +819,16 @@ template inline void InterceptServerInitialMetadata( absl::Status (Derived::Call::*fn)(ServerMetadata&, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerInitialMetadata); call_spine->server_initial_metadata().sender.InterceptAndMap( [call, call_spine, channel]( ServerMetadataHandle md) -> absl::optional { auto status = call->OnServerInitialMetadata(*md, channel); if (status.ok()) return std::move(md); - return call_spine->Cancel(ServerMetadataFromStatus(status)); + call_spine->PullServerTrailingMetadata( + ServerMetadataFromStatus(status)); + return absl::nullopt; }); } @@ -885,13 +900,14 @@ inline void InterceptServerToClientMessage(const NoInterceptor*, void*, void*, template inline void InterceptServerToClientMessage( ServerMetadataHandle (Derived::Call::*fn)(const Message&), - typename Derived::Call* call, Derived*, CallSpineInterface* call_spine) { + typename Derived::Call* call, Derived*, PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerToClientMessage); call_spine->server_to_client_messages().sender.InterceptAndMap( [call, call_spine](MessageHandle msg) -> absl::optional { auto return_md = call->OnServerToClientMessage(*msg); if (return_md == nullptr) return std::move(msg); - return call_spine->Cancel(std::move(return_md)); + call_spine->PushServerTrailingMetadata(std::move(return_md)); + return absl::nullopt; }); } @@ -899,14 +915,15 @@ template inline void InterceptServerToClientMessage( ServerMetadataHandle (Derived::Call::*fn)(const Message&, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerToClientMessage); call_spine->server_to_client_messages().sender.InterceptAndMap( [call, call_spine, channel](MessageHandle msg) -> absl::optional { auto return_md = call->OnServerToClientMessage(*msg, channel); if (return_md == nullptr) return std::move(msg); - return call_spine->Cancel(std::move(return_md)); + call_spine->PushServerTrailingMetadata(std::move(return_md)); + return absl::nullopt; }); } @@ -914,7 +931,7 @@ template inline void InterceptServerToClientMessage( MessageHandle (Derived::Call::*fn)(MessageHandle, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerToClientMessage); call_spine->server_to_client_messages().sender.InterceptAndMap( [call, channel](MessageHandle msg) { @@ -926,14 +943,16 @@ template inline void InterceptServerToClientMessage( absl::StatusOr (Derived::Call::*fn)(MessageHandle, Derived*), typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { + PipeBasedCallSpine* call_spine) { GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerToClientMessage); call_spine->server_to_client_messages().sender.InterceptAndMap( [call, call_spine, channel](MessageHandle msg) -> absl::optional { auto r = call->OnServerToClientMessage(std::move(msg), channel); if (r.ok()) return std::move(*r); - return call_spine->Cancel(ServerMetadataFromStatus(r.status())); + call_spine->PushServerTrailingMetadata( + ServerMetadataFromStatus(r.status())); + return absl::nullopt; }); } @@ -942,40 +961,25 @@ inline void InterceptServerTrailingMetadata(const NoInterceptor*, void*, void*, template inline void InterceptServerTrailingMetadata( - void (Derived::Call::*fn)(ServerMetadata&), typename Derived::Call* call, - Derived*, CallSpineInterface* call_spine) { - GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerTrailingMetadata); - call_spine->server_trailing_metadata().sender.InterceptAndMap( - [call](ServerMetadataHandle md) { - call->OnServerTrailingMetadata(*md); - return md; - }); + void (Derived::Call::*)(ServerMetadata&), typename Derived::Call*, Derived*, + PipeBasedCallSpine*) { + gpr_log(GPR_ERROR, + "InterceptServerTrailingMetadata not available for call v2.5"); } - template inline void InterceptServerTrailingMetadata( - void (Derived::Call::*fn)(ServerMetadata&, Derived*), - typename Derived::Call* call, Derived* channel, - CallSpineInterface* call_spine) { - GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerTrailingMetadata); - call_spine->server_trailing_metadata().sender.InterceptAndMap( - [call, channel](ServerMetadataHandle md) { - call->OnServerTrailingMetadata(*md, channel); - return md; - }); + void (Derived::Call::*)(ServerMetadata&, Derived*), typename Derived::Call*, + Derived*, PipeBasedCallSpine*) { + gpr_log(GPR_ERROR, + "InterceptServerTrailingMetadata not available for call v2.5"); } template inline void InterceptServerTrailingMetadata( - absl::Status (Derived::Call::*fn)(ServerMetadata&), - typename Derived::Call* call, Derived*, CallSpineInterface* call_spine) { - GPR_DEBUG_ASSERT(fn == &Derived::Call::OnServerTrailingMetadata); - call_spine->server_trailing_metadata().sender.InterceptAndMap( - [call](ServerMetadataHandle md) -> absl::optional { - auto status = call->OnServerTrailingMetadata(*md); - if (status.ok()) return std::move(md); - return ServerMetadataFromStatus(status); - }); + absl::Status (Derived::Call::*)(ServerMetadata&), typename Derived::Call*, + Derived*, PipeBasedCallSpine*) { + gpr_log(GPR_ERROR, + "InterceptServerTrailingMetadata not available for call v2.5"); } inline void InterceptFinalize(const NoInterceptor*, void*, void*) {} @@ -1085,23 +1089,20 @@ class ImplementChannelFilter : public ChannelFilter, GetContext() ->ManagedNew>( static_cast(this)); + auto* c = DownCast(call_spine); + auto* d = static_cast(this); promise_filter_detail::InterceptClientInitialMetadata( - &Derived::Call::OnClientInitialMetadata, call, - static_cast(this), call_spine); + &Derived::Call::OnClientInitialMetadata, call, d, c); promise_filter_detail::InterceptClientToServerMessage( - &Derived::Call::OnClientToServerMessage, call, - static_cast(this), call_spine); + &Derived::Call::OnClientToServerMessage, call, d, c); promise_filter_detail::InterceptServerInitialMetadata( - &Derived::Call::OnServerInitialMetadata, call, - static_cast(this), call_spine); + &Derived::Call::OnServerInitialMetadata, call, d, c); promise_filter_detail::InterceptServerToClientMessage( - &Derived::Call::OnServerToClientMessage, call, - static_cast(this), call_spine); + &Derived::Call::OnServerToClientMessage, call, d, c); promise_filter_detail::InterceptServerTrailingMetadata( - &Derived::Call::OnServerTrailingMetadata, call, - static_cast(this), call_spine); - promise_filter_detail::InterceptFinalize(&Derived::Call::OnFinalize, - static_cast(this), call); + &Derived::Call::OnServerTrailingMetadata, call, d, c); + promise_filter_detail::InterceptFinalize(&Derived::Call::OnFinalize, d, + call); } // Polyfill for the original promise scheme. @@ -1840,6 +1841,15 @@ struct BaseCallDataMethods { } }; +// The type of object returned by a filter's Create method. +template +using CreatedType = typename decltype(T::Create(ChannelArgs(), {}))::value_type; + +template +inline ChannelFilter* ChannelFilterFromElem(GrpcChannelOrCallElement* elem) { + return *static_cast(elem->channel_data); +} + template struct CallDataFilterWithFlagsMethods { static absl::Status InitCallElem(grpc_call_element* elem, @@ -1864,32 +1874,25 @@ struct ChannelFilterMethods { static ArenaPromise MakeCallPromise( grpc_channel_element* elem, CallArgs call_args, NextPromiseFactory next_promise_factory) { - return static_cast(elem->channel_data) - ->MakeCallPromise(std::move(call_args), - std::move(next_promise_factory)); + return ChannelFilterFromElem(elem)->MakeCallPromise( + std::move(call_args), std::move(next_promise_factory)); } static void StartTransportOp(grpc_channel_element* elem, grpc_transport_op* op) { - if (!static_cast(elem->channel_data) - ->StartTransportOp(op)) { + if (!ChannelFilterFromElem(elem)->StartTransportOp(op)) { grpc_channel_next_op(elem, op); } } static void PostInitChannelElem(grpc_channel_stack*, grpc_channel_element* elem) { - static_cast(elem->channel_data)->PostInit(); - } - - static void DestroyChannelElem(grpc_channel_element* elem) { - static_cast(elem->channel_data)->~ChannelFilter(); + ChannelFilterFromElem(elem)->PostInit(); } static void GetChannelInfo(grpc_channel_element* elem, const grpc_channel_info* info) { - if (!static_cast(elem->channel_data) - ->GetChannelInfo(info)) { + if (!ChannelFilterFromElem(elem)->GetChannelInfo(info)) { grpc_channel_next_get_info(elem, info); } } @@ -1903,15 +1906,16 @@ struct ChannelFilterWithFlagsMethods { auto status = F::Create(args->channel_args, ChannelFilter::Args(args->channel_stack, elem)); if (!status.ok()) { - static_assert( - sizeof(promise_filter_detail::InvalidChannelFilter) <= sizeof(F), - "InvalidChannelFilter must fit in F"); - new (elem->channel_data) promise_filter_detail::InvalidChannelFilter(); + new (elem->channel_data) F*(nullptr); return absl_status_to_grpc_error(status.status()); } - new (elem->channel_data) F(std::move(*status)); + new (elem->channel_data) F*(status->release()); return absl::OkStatus(); } + + static void DestroyChannelElem(grpc_channel_element* elem) { + CreatedType channel_elem(DownCast(ChannelFilterFromElem(elem))); + } }; } // namespace promise_filter_detail @@ -1957,7 +1961,8 @@ MakePromiseBasedFilter(const char* name) { // post_init_channel_elem promise_filter_detail::ChannelFilterMethods::PostInitChannelElem, // destroy_channel_elem - promise_filter_detail::ChannelFilterMethods::DestroyChannelElem, + promise_filter_detail::ChannelFilterWithFlagsMethods< + F, kFlags>::DestroyChannelElem, // get_channel_info promise_filter_detail::ChannelFilterMethods::GetChannelInfo, // name @@ -2003,7 +2008,8 @@ MakePromiseBasedFilter(const char* name) { // post_init_channel_elem promise_filter_detail::ChannelFilterMethods::PostInitChannelElem, // destroy_channel_elem - promise_filter_detail::ChannelFilterMethods::DestroyChannelElem, + promise_filter_detail::ChannelFilterWithFlagsMethods< + F, kFlags>::DestroyChannelElem, // get_channel_info promise_filter_detail::ChannelFilterMethods::GetChannelInfo, // name @@ -2045,7 +2051,8 @@ MakePromiseBasedFilter(const char* name) { // post_init_channel_elem promise_filter_detail::ChannelFilterMethods::PostInitChannelElem, // destroy_channel_elem - promise_filter_detail::ChannelFilterMethods::DestroyChannelElem, + promise_filter_detail::ChannelFilterWithFlagsMethods< + F, kFlags>::DestroyChannelElem, // get_channel_info promise_filter_detail::ChannelFilterMethods::GetChannelInfo, // name diff --git a/src/core/lib/channel/server_call_tracer_filter.cc b/src/core/lib/channel/server_call_tracer_filter.cc index dbf628d8b83..5effe8f8538 100644 --- a/src/core/lib/channel/server_call_tracer_filter.cc +++ b/src/core/lib/channel/server_call_tracer_filter.cc @@ -17,6 +17,7 @@ #include "src/core/lib/channel/server_call_tracer_filter.h" #include +#include #include #include "absl/status/status.h" @@ -49,7 +50,7 @@ class ServerCallTracerFilter public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& /*args*/, ChannelFilter::Args /*filter_args*/); class Call { @@ -98,14 +99,16 @@ const grpc_channel_filter ServerCallTracerFilter::kFilter = kFilterExaminesServerInitialMetadata>( "server_call_tracer"); -absl::StatusOr ServerCallTracerFilter::Create( - const ChannelArgs& /*args*/, ChannelFilter::Args /*filter_args*/) { - return ServerCallTracerFilter(); +absl::StatusOr> +ServerCallTracerFilter::Create(const ChannelArgs& /*args*/, + ChannelFilter::Args /*filter_args*/) { + return std::make_unique(); } } // namespace void RegisterServerCallTracerFilter(CoreConfiguration::Builder* builder) { + if (IsChaoticGoodEnabled()) return; builder->channel_init()->RegisterFilter( GRPC_SERVER_CHANNEL); } diff --git a/src/core/lib/event_engine/extensions/supports_fd.h b/src/core/lib/event_engine/extensions/supports_fd.h index 66ea1c2b345..30f0d2ad0e6 100644 --- a/src/core/lib/event_engine/extensions/supports_fd.h +++ b/src/core/lib/event_engine/extensions/supports_fd.h @@ -112,6 +112,13 @@ class EventEngineSupportsFdExtension { int fd, const EndpointConfig& config, MemoryAllocator memory_allocator) = 0; + /// Creates an EventEngine::Endpoint from an fd which is already assumed to be + /// connected to a remote peer. See \a CreatePosixEndpointFromFd for details. + /// This has the same behavior, but the \a memory_allocator is taken from the + /// EndpointConfig's resource quota. + virtual std::unique_ptr CreateEndpointFromFd( + int fd, const EndpointConfig& config) = 0; + /// Called when the posix listener has accepted a new client connection. /// \a listener_fd - The listening socket fd that accepted the new client /// connection. diff --git a/src/core/lib/event_engine/posix_engine/posix_engine.cc b/src/core/lib/event_engine/posix_engine/posix_engine.cc index 275e0dcbf65..0ac3dfcebfe 100644 --- a/src/core/lib/event_engine/posix_engine/posix_engine.cc +++ b/src/core/lib/event_engine/posix_engine/posix_engine.cc @@ -661,7 +661,7 @@ PosixEventEngine::CreatePosixEndpointFromFd(int fd, const EndpointConfig& config, MemoryAllocator memory_allocator) { #if GRPC_PLATFORM_SUPPORTS_POSIX_POLLING - GPR_DEBUG_ASSERT(fd > 0); + GPR_ASSERT(fd > 0); PosixEventPoller* poller = poller_manager_->Poller(); GPR_DEBUG_ASSERT(poller != nullptr); EventHandle* handle = @@ -676,6 +676,22 @@ PosixEventEngine::CreatePosixEndpointFromFd(int fd, #endif // GRPC_PLATFORM_SUPPORTS_POSIX_POLLING } +std::unique_ptr PosixEventEngine::CreateEndpointFromFd( + int fd, const EndpointConfig& config) { + auto options = TcpOptionsFromEndpointConfig(config); + MemoryAllocator allocator; + if (options.memory_allocator_factory != nullptr) { + return CreatePosixEndpointFromFd( + fd, config, + options.memory_allocator_factory->CreateMemoryAllocator( + absl::StrCat("allocator:", fd))); + } + return CreatePosixEndpointFromFd( + fd, config, + options.resource_quota->memory_quota()->CreateMemoryAllocator( + absl::StrCat("allocator:", fd))); +} + absl::StatusOr> PosixEventEngine::CreateListener( Listener::AcceptCallback on_accept, diff --git a/src/core/lib/event_engine/posix_engine/posix_engine.h b/src/core/lib/event_engine/posix_engine/posix_engine.h index 257cd6b34b5..ea426c379c9 100644 --- a/src/core/lib/event_engine/posix_engine/posix_engine.h +++ b/src/core/lib/event_engine/posix_engine/posix_engine.h @@ -172,6 +172,8 @@ class PosixEventEngine final : public PosixEventEngineWithFdSupport, std::unique_ptr CreatePosixEndpointFromFd( int fd, const EndpointConfig& config, MemoryAllocator memory_allocator) override; + std::unique_ptr CreateEndpointFromFd( + int fd, const EndpointConfig& config) override; absl::StatusOr> CreateListener( Listener::AcceptCallback on_accept, diff --git a/src/core/lib/experiments/experiments.cc b/src/core/lib/experiments/experiments.cc index 9eee1458bec..3f9e6a840ca 100644 --- a/src/core/lib/experiments/experiments.cc +++ b/src/core/lib/experiments/experiments.cc @@ -48,6 +48,9 @@ const char* const additional_constraints_event_engine_listener = "{}"; const char* const description_free_large_allocator = "If set, return all free bytes from a \042big\042 allocator"; const char* const additional_constraints_free_large_allocator = "{}"; +const char* const description_http2_stats_fix = + "Fix on HTTP2 outgoing data stats reporting"; +const char* const additional_constraints_http2_stats_fix = "{}"; const char* const description_keepalive_fix = "Allows overriding keepalive_permit_without_calls. Refer " "https://github.com/grpc/grpc/pull/33428 for more information."; @@ -139,11 +142,6 @@ const char* const description_work_serializer_dispatch = const char* const additional_constraints_work_serializer_dispatch = "{}"; const uint8_t required_experiments_work_serializer_dispatch[] = { static_cast(grpc_core::kExperimentIdEventEngineClient)}; -#ifdef NDEBUG -const bool kDefaultForDebugOnly = false; -#else -const bool kDefaultForDebugOnly = true; -#endif } // namespace namespace grpc_core { @@ -152,7 +150,7 @@ const ExperimentMetadata g_experiment_metadata[] = { {"call_status_override_on_cancellation", description_call_status_override_on_cancellation, additional_constraints_call_status_override_on_cancellation, nullptr, 0, - kDefaultForDebugOnly, true}, + true, true}, {"call_v3", description_call_v3, additional_constraints_call_v3, nullptr, 0, false, true}, {"canary_client_privacy", description_canary_client_privacy, @@ -167,6 +165,8 @@ const ExperimentMetadata g_experiment_metadata[] = { additional_constraints_event_engine_listener, nullptr, 0, false, true}, {"free_large_allocator", description_free_large_allocator, additional_constraints_free_large_allocator, nullptr, 0, false, true}, + {"http2_stats_fix", description_http2_stats_fix, + additional_constraints_http2_stats_fix, nullptr, 0, true, true}, {"keepalive_fix", description_keepalive_fix, additional_constraints_keepalive_fix, nullptr, 0, false, false}, {"keepalive_server_fix", description_keepalive_server_fix, @@ -206,7 +206,7 @@ const ExperimentMetadata g_experiment_metadata[] = { {"tcp_rcv_lowat", description_tcp_rcv_lowat, additional_constraints_tcp_rcv_lowat, nullptr, 0, false, true}, {"trace_record_callops", description_trace_record_callops, - additional_constraints_trace_record_callops, nullptr, 0, false, true}, + additional_constraints_trace_record_callops, nullptr, 0, true, true}, {"unconstrained_max_quota_buffer_size", description_unconstrained_max_quota_buffer_size, additional_constraints_unconstrained_max_quota_buffer_size, nullptr, 0, @@ -248,6 +248,9 @@ const char* const additional_constraints_event_engine_listener = "{}"; const char* const description_free_large_allocator = "If set, return all free bytes from a \042big\042 allocator"; const char* const additional_constraints_free_large_allocator = "{}"; +const char* const description_http2_stats_fix = + "Fix on HTTP2 outgoing data stats reporting"; +const char* const additional_constraints_http2_stats_fix = "{}"; const char* const description_keepalive_fix = "Allows overriding keepalive_permit_without_calls. Refer " "https://github.com/grpc/grpc/pull/33428 for more information."; @@ -339,11 +342,6 @@ const char* const description_work_serializer_dispatch = const char* const additional_constraints_work_serializer_dispatch = "{}"; const uint8_t required_experiments_work_serializer_dispatch[] = { static_cast(grpc_core::kExperimentIdEventEngineClient)}; -#ifdef NDEBUG -const bool kDefaultForDebugOnly = false; -#else -const bool kDefaultForDebugOnly = true; -#endif } // namespace namespace grpc_core { @@ -352,7 +350,7 @@ const ExperimentMetadata g_experiment_metadata[] = { {"call_status_override_on_cancellation", description_call_status_override_on_cancellation, additional_constraints_call_status_override_on_cancellation, nullptr, 0, - kDefaultForDebugOnly, true}, + true, true}, {"call_v3", description_call_v3, additional_constraints_call_v3, nullptr, 0, false, true}, {"canary_client_privacy", description_canary_client_privacy, @@ -367,6 +365,8 @@ const ExperimentMetadata g_experiment_metadata[] = { additional_constraints_event_engine_listener, nullptr, 0, true, true}, {"free_large_allocator", description_free_large_allocator, additional_constraints_free_large_allocator, nullptr, 0, false, true}, + {"http2_stats_fix", description_http2_stats_fix, + additional_constraints_http2_stats_fix, nullptr, 0, true, true}, {"keepalive_fix", description_keepalive_fix, additional_constraints_keepalive_fix, nullptr, 0, false, false}, {"keepalive_server_fix", description_keepalive_server_fix, @@ -406,7 +406,7 @@ const ExperimentMetadata g_experiment_metadata[] = { {"tcp_rcv_lowat", description_tcp_rcv_lowat, additional_constraints_tcp_rcv_lowat, nullptr, 0, false, true}, {"trace_record_callops", description_trace_record_callops, - additional_constraints_trace_record_callops, nullptr, 0, false, true}, + additional_constraints_trace_record_callops, nullptr, 0, true, true}, {"unconstrained_max_quota_buffer_size", description_unconstrained_max_quota_buffer_size, additional_constraints_unconstrained_max_quota_buffer_size, nullptr, 0, @@ -448,6 +448,9 @@ const char* const additional_constraints_event_engine_listener = "{}"; const char* const description_free_large_allocator = "If set, return all free bytes from a \042big\042 allocator"; const char* const additional_constraints_free_large_allocator = "{}"; +const char* const description_http2_stats_fix = + "Fix on HTTP2 outgoing data stats reporting"; +const char* const additional_constraints_http2_stats_fix = "{}"; const char* const description_keepalive_fix = "Allows overriding keepalive_permit_without_calls. Refer " "https://github.com/grpc/grpc/pull/33428 for more information."; @@ -539,11 +542,6 @@ const char* const description_work_serializer_dispatch = const char* const additional_constraints_work_serializer_dispatch = "{}"; const uint8_t required_experiments_work_serializer_dispatch[] = { static_cast(grpc_core::kExperimentIdEventEngineClient)}; -#ifdef NDEBUG -const bool kDefaultForDebugOnly = false; -#else -const bool kDefaultForDebugOnly = true; -#endif } // namespace namespace grpc_core { @@ -552,7 +550,7 @@ const ExperimentMetadata g_experiment_metadata[] = { {"call_status_override_on_cancellation", description_call_status_override_on_cancellation, additional_constraints_call_status_override_on_cancellation, nullptr, 0, - kDefaultForDebugOnly, true}, + true, true}, {"call_v3", description_call_v3, additional_constraints_call_v3, nullptr, 0, false, true}, {"canary_client_privacy", description_canary_client_privacy, @@ -567,6 +565,8 @@ const ExperimentMetadata g_experiment_metadata[] = { additional_constraints_event_engine_listener, nullptr, 0, true, true}, {"free_large_allocator", description_free_large_allocator, additional_constraints_free_large_allocator, nullptr, 0, false, true}, + {"http2_stats_fix", description_http2_stats_fix, + additional_constraints_http2_stats_fix, nullptr, 0, true, true}, {"keepalive_fix", description_keepalive_fix, additional_constraints_keepalive_fix, nullptr, 0, false, false}, {"keepalive_server_fix", description_keepalive_server_fix, @@ -606,7 +606,7 @@ const ExperimentMetadata g_experiment_metadata[] = { {"tcp_rcv_lowat", description_tcp_rcv_lowat, additional_constraints_tcp_rcv_lowat, nullptr, 0, false, true}, {"trace_record_callops", description_trace_record_callops, - additional_constraints_trace_record_callops, nullptr, 0, false, true}, + additional_constraints_trace_record_callops, nullptr, 0, true, true}, {"unconstrained_max_quota_buffer_size", description_unconstrained_max_quota_buffer_size, additional_constraints_unconstrained_max_quota_buffer_size, nullptr, 0, diff --git a/src/core/lib/experiments/experiments.h b/src/core/lib/experiments/experiments.h index a48a97d63dc..faf13fca4cf 100644 --- a/src/core/lib/experiments/experiments.h +++ b/src/core/lib/experiments/experiments.h @@ -57,16 +57,8 @@ namespace grpc_core { #ifdef GRPC_EXPERIMENTS_ARE_FINAL #if defined(GRPC_CFSTREAM) -#ifndef NDEBUG #define GRPC_EXPERIMENT_IS_INCLUDED_CALL_STATUS_OVERRIDE_ON_CANCELLATION -#endif -inline bool IsCallStatusOverrideOnCancellationEnabled() { -#ifdef NDEBUG - return false; -#else - return true; -#endif -} +inline bool IsCallStatusOverrideOnCancellationEnabled() { return true; } inline bool IsCallV3Enabled() { return false; } inline bool IsCanaryClientPrivacyEnabled() { return false; } inline bool IsClientPrivacyEnabled() { return false; } @@ -74,6 +66,8 @@ inline bool IsEventEngineClientEnabled() { return false; } inline bool IsEventEngineDnsEnabled() { return false; } inline bool IsEventEngineListenerEnabled() { return false; } inline bool IsFreeLargeAllocatorEnabled() { return false; } +#define GRPC_EXPERIMENT_IS_INCLUDED_HTTP2_STATS_FIX +inline bool IsHttp2StatsFixEnabled() { return true; } inline bool IsKeepaliveFixEnabled() { return false; } inline bool IsKeepaliveServerFixEnabled() { return false; } #define GRPC_EXPERIMENT_IS_INCLUDED_MONITORING_EXPERIMENT @@ -93,23 +87,16 @@ inline bool IsScheduleCancellationOverWriteEnabled() { return false; } inline bool IsServerPrivacyEnabled() { return false; } inline bool IsTcpFrameSizeTuningEnabled() { return false; } inline bool IsTcpRcvLowatEnabled() { return false; } -inline bool IsTraceRecordCallopsEnabled() { return false; } +#define GRPC_EXPERIMENT_IS_INCLUDED_TRACE_RECORD_CALLOPS +inline bool IsTraceRecordCallopsEnabled() { return true; } inline bool IsUnconstrainedMaxQuotaBufferSizeEnabled() { return false; } #define GRPC_EXPERIMENT_IS_INCLUDED_WORK_SERIALIZER_CLEARS_TIME_CACHE inline bool IsWorkSerializerClearsTimeCacheEnabled() { return true; } inline bool IsWorkSerializerDispatchEnabled() { return false; } #elif defined(GPR_WINDOWS) -#ifndef NDEBUG #define GRPC_EXPERIMENT_IS_INCLUDED_CALL_STATUS_OVERRIDE_ON_CANCELLATION -#endif -inline bool IsCallStatusOverrideOnCancellationEnabled() { -#ifdef NDEBUG - return false; -#else - return true; -#endif -} +inline bool IsCallStatusOverrideOnCancellationEnabled() { return true; } inline bool IsCallV3Enabled() { return false; } inline bool IsCanaryClientPrivacyEnabled() { return false; } inline bool IsClientPrivacyEnabled() { return false; } @@ -118,6 +105,8 @@ inline bool IsEventEngineDnsEnabled() { return false; } #define GRPC_EXPERIMENT_IS_INCLUDED_EVENT_ENGINE_LISTENER inline bool IsEventEngineListenerEnabled() { return true; } inline bool IsFreeLargeAllocatorEnabled() { return false; } +#define GRPC_EXPERIMENT_IS_INCLUDED_HTTP2_STATS_FIX +inline bool IsHttp2StatsFixEnabled() { return true; } inline bool IsKeepaliveFixEnabled() { return false; } inline bool IsKeepaliveServerFixEnabled() { return false; } #define GRPC_EXPERIMENT_IS_INCLUDED_MONITORING_EXPERIMENT @@ -137,23 +126,16 @@ inline bool IsScheduleCancellationOverWriteEnabled() { return false; } inline bool IsServerPrivacyEnabled() { return false; } inline bool IsTcpFrameSizeTuningEnabled() { return false; } inline bool IsTcpRcvLowatEnabled() { return false; } -inline bool IsTraceRecordCallopsEnabled() { return false; } +#define GRPC_EXPERIMENT_IS_INCLUDED_TRACE_RECORD_CALLOPS +inline bool IsTraceRecordCallopsEnabled() { return true; } inline bool IsUnconstrainedMaxQuotaBufferSizeEnabled() { return false; } #define GRPC_EXPERIMENT_IS_INCLUDED_WORK_SERIALIZER_CLEARS_TIME_CACHE inline bool IsWorkSerializerClearsTimeCacheEnabled() { return true; } inline bool IsWorkSerializerDispatchEnabled() { return false; } #else -#ifndef NDEBUG #define GRPC_EXPERIMENT_IS_INCLUDED_CALL_STATUS_OVERRIDE_ON_CANCELLATION -#endif -inline bool IsCallStatusOverrideOnCancellationEnabled() { -#ifdef NDEBUG - return false; -#else - return true; -#endif -} +inline bool IsCallStatusOverrideOnCancellationEnabled() { return true; } inline bool IsCallV3Enabled() { return false; } inline bool IsCanaryClientPrivacyEnabled() { return false; } inline bool IsClientPrivacyEnabled() { return false; } @@ -163,6 +145,8 @@ inline bool IsEventEngineDnsEnabled() { return true; } #define GRPC_EXPERIMENT_IS_INCLUDED_EVENT_ENGINE_LISTENER inline bool IsEventEngineListenerEnabled() { return true; } inline bool IsFreeLargeAllocatorEnabled() { return false; } +#define GRPC_EXPERIMENT_IS_INCLUDED_HTTP2_STATS_FIX +inline bool IsHttp2StatsFixEnabled() { return true; } inline bool IsKeepaliveFixEnabled() { return false; } inline bool IsKeepaliveServerFixEnabled() { return false; } #define GRPC_EXPERIMENT_IS_INCLUDED_MONITORING_EXPERIMENT @@ -182,7 +166,8 @@ inline bool IsScheduleCancellationOverWriteEnabled() { return false; } inline bool IsServerPrivacyEnabled() { return false; } inline bool IsTcpFrameSizeTuningEnabled() { return false; } inline bool IsTcpRcvLowatEnabled() { return false; } -inline bool IsTraceRecordCallopsEnabled() { return false; } +#define GRPC_EXPERIMENT_IS_INCLUDED_TRACE_RECORD_CALLOPS +inline bool IsTraceRecordCallopsEnabled() { return true; } inline bool IsUnconstrainedMaxQuotaBufferSizeEnabled() { return false; } #define GRPC_EXPERIMENT_IS_INCLUDED_WORK_SERIALIZER_CLEARS_TIME_CACHE inline bool IsWorkSerializerClearsTimeCacheEnabled() { return true; } @@ -200,6 +185,7 @@ enum ExperimentIds { kExperimentIdEventEngineDns, kExperimentIdEventEngineListener, kExperimentIdFreeLargeAllocator, + kExperimentIdHttp2StatsFix, kExperimentIdKeepaliveFix, kExperimentIdKeepaliveServerFix, kExperimentIdMonitoringExperiment, @@ -254,6 +240,10 @@ inline bool IsEventEngineListenerEnabled() { inline bool IsFreeLargeAllocatorEnabled() { return IsExperimentEnabled(kExperimentIdFreeLargeAllocator); } +#define GRPC_EXPERIMENT_IS_INCLUDED_HTTP2_STATS_FIX +inline bool IsHttp2StatsFixEnabled() { + return IsExperimentEnabled(kExperimentIdHttp2StatsFix); +} #define GRPC_EXPERIMENT_IS_INCLUDED_KEEPALIVE_FIX inline bool IsKeepaliveFixEnabled() { return IsExperimentEnabled(kExperimentIdKeepaliveFix); diff --git a/src/core/lib/experiments/experiments.yaml b/src/core/lib/experiments/experiments.yaml index 9ab849a823b..9be9619ff3c 100644 --- a/src/core/lib/experiments/experiments.yaml +++ b/src/core/lib/experiments/experiments.yaml @@ -44,7 +44,7 @@ description: Avoid overriding call status of successfully finished calls if it races with cancellation. - expiry: 2024/04/01 + expiry: 2024/08/01 owner: vigneshbabu@google.com test_tags: [] - name: call_v3 @@ -98,6 +98,12 @@ expiry: 2024/08/01 owner: alishananda@google.com test_tags: [resource_quota_test] +- name: http2_stats_fix + description: + Fix on HTTP2 outgoing data stats reporting + expiry: 2024/09/30 + owner: yashkt@google.com + test_tags: [] - name: keepalive_fix description: Allows overriding keepalive_permit_without_calls. @@ -180,7 +186,7 @@ test_tags: [flow_control_test] - name: schedule_cancellation_over_write description: Allow cancellation op to be scheduled over a write - expiry: 2024/04/01 + expiry: 2024/08/01 owner: vigneshbabu@google.com test_tags: [] - name: server_privacy @@ -206,7 +212,7 @@ test_tags: ["endpoint_test", "flow_control_test"] - name: trace_record_callops description: Enables tracing of call batch initiation and completion. - expiry: 2024/04/01 + expiry: 2024/08/01 owner: vigneshbabu@google.com test_tags: [] - name: unconstrained_max_quota_buffer_size diff --git a/src/core/lib/experiments/rollouts.yaml b/src/core/lib/experiments/rollouts.yaml index 787265a2da2..ce9cf80c114 100644 --- a/src/core/lib/experiments/rollouts.yaml +++ b/src/core/lib/experiments/rollouts.yaml @@ -41,7 +41,7 @@ # Supported platforms: ios, windows, posix - name: call_status_override_on_cancellation - default: debug + default: true - name: call_v3 default: false - name: canary_client_privacy @@ -109,7 +109,7 @@ - name: tcp_rcv_lowat default: false - name: trace_record_callops - default: false + default: true - name: unconstrained_max_quota_buffer_size default: false - name: work_serializer_clears_time_cache diff --git a/src/core/lib/http/httpcli_security_connector.cc b/src/core/lib/http/httpcli_security_connector.cc index 28127811b2d..f5acf5bc3ba 100644 --- a/src/core/lib/http/httpcli_security_connector.cc +++ b/src/core/lib/http/httpcli_security_connector.cc @@ -25,6 +25,7 @@ #include "absl/strings/string_view.h" #include "absl/types/optional.h" +#include #include #include #include diff --git a/src/core/lib/promise/for_each.h b/src/core/lib/promise/for_each.h index 4f431a9c4a9..82322add349 100644 --- a/src/core/lib/promise/for_each.h +++ b/src/core/lib/promise/for_each.h @@ -56,13 +56,52 @@ struct Done { static StatusFlag Make(bool cancelled) { return StatusFlag(!cancelled); } }; +template +struct NextValueTraits; + +enum class NextValueType { + kValue, + kEndOfStream, + kError, +}; + +template +struct NextValueTraits> { + using Value = typename T::value_type; + + static NextValueType Type(const T& t) { + if (t.has_value()) return NextValueType::kValue; + if (t.cancelled()) return NextValueType::kError; + return NextValueType::kEndOfStream; + } + + static Value& MutableValue(T& t) { return *t; } +}; + +template +struct NextValueTraits>> { + using Value = T; + + static NextValueType Type(const ValueOrFailure>& t) { + if (t.ok()) { + if (t.value().has_value()) return NextValueType::kValue; + return NextValueType::kEndOfStream; + } + return NextValueType::kError; + } + + static Value& MutableValue(ValueOrFailure>& t) { + return **t; + } +}; + template class ForEach { private: using ReaderNext = decltype(std::declval().Next()); using ReaderResult = typename PollTraits()())>::Type; - using ReaderResultValue = typename ReaderResult::value_type; + using ReaderResultValue = typename NextValueTraits::Value; using ActionFactory = promise_detail::RepeatedPromiseFactory; using ActionPromise = typename ActionFactory::Promise; @@ -120,22 +159,37 @@ class ForEach { Poll PollReaderNext() { if (grpc_trace_promise_primitives.enabled()) { - gpr_log(GPR_DEBUG, "%s PollReaderNext", DebugTag().c_str()); + gpr_log(GPR_INFO, "%s PollReaderNext", DebugTag().c_str()); } auto r = reader_next_(); if (auto* p = r.value_if_ready()) { - if (grpc_trace_promise_primitives.enabled()) { - gpr_log(GPR_DEBUG, "%s PollReaderNext: got has_value=%s", - DebugTag().c_str(), p->has_value() ? "true" : "false"); - } - if (p->has_value()) { - Destruct(&reader_next_); - auto action = action_factory_.Make(std::move(**p)); - Construct(&in_action_, std::move(action), std::move(*p)); - reading_next_ = false; - return PollAction(); - } else { - return Done::Make(p->cancelled()); + switch (NextValueTraits::Type(*p)) { + case NextValueType::kValue: { + if (grpc_trace_promise_primitives.enabled()) { + gpr_log(GPR_INFO, "%s PollReaderNext: got value", + DebugTag().c_str()); + } + Destruct(&reader_next_); + auto action = action_factory_.Make( + std::move(NextValueTraits::MutableValue(*p))); + Construct(&in_action_, std::move(action), std::move(*p)); + reading_next_ = false; + return PollAction(); + } + case NextValueType::kEndOfStream: { + if (grpc_trace_promise_primitives.enabled()) { + gpr_log(GPR_INFO, "%s PollReaderNext: got end of stream", + DebugTag().c_str()); + } + return Done::Make(false); + } + case NextValueType::kError: { + if (grpc_trace_promise_primitives.enabled()) { + gpr_log(GPR_INFO, "%s PollReaderNext: got error", + DebugTag().c_str()); + } + return Done::Make(true); + } } } return Pending(); @@ -143,7 +197,7 @@ class ForEach { Poll PollAction() { if (grpc_trace_promise_primitives.enabled()) { - gpr_log(GPR_DEBUG, "%s PollAction", DebugTag().c_str()); + gpr_log(GPR_INFO, "%s PollAction", DebugTag().c_str()); } auto r = in_action_.promise(); if (auto* p = r.value_if_ready()) { diff --git a/src/core/lib/promise/pipe.h b/src/core/lib/promise/pipe.h index a1533bbcae5..f56567e6cf2 100644 --- a/src/core/lib/promise/pipe.h +++ b/src/core/lib/promise/pipe.h @@ -89,7 +89,7 @@ class NextResult final { const T& operator*() const; T& operator*(); // Only valid if !has_value() - bool cancelled() { return cancelled_; } + bool cancelled() const { return cancelled_; } private: RefCountedPtr> center_; diff --git a/src/core/lib/security/authorization/grpc_server_authz_filter.cc b/src/core/lib/security/authorization/grpc_server_authz_filter.cc index 199c0a8fa5b..5474847701a 100644 --- a/src/core/lib/security/authorization/grpc_server_authz_filter.cc +++ b/src/core/lib/security/authorization/grpc_server_authz_filter.cc @@ -51,14 +51,14 @@ GrpcServerAuthzFilter::GrpcServerAuthzFilter( per_channel_evaluate_args_(auth_context_.get(), args), provider_(std::move(provider)) {} -absl::StatusOr GrpcServerAuthzFilter::Create( - const ChannelArgs& args, ChannelFilter::Args) { +absl::StatusOr> +GrpcServerAuthzFilter::Create(const ChannelArgs& args, ChannelFilter::Args) { auto* auth_context = args.GetObject(); auto* provider = args.GetObject(); if (provider == nullptr) { return absl::InvalidArgumentError("Failed to get authorization provider."); } - return GrpcServerAuthzFilter( + return std::make_unique( auth_context != nullptr ? auth_context->Ref() : nullptr, args, provider->Ref()); } diff --git a/src/core/lib/security/authorization/grpc_server_authz_filter.h b/src/core/lib/security/authorization/grpc_server_authz_filter.h index fd29197a3bf..b4b0a7463cd 100644 --- a/src/core/lib/security/authorization/grpc_server_authz_filter.h +++ b/src/core/lib/security/authorization/grpc_server_authz_filter.h @@ -37,8 +37,12 @@ class GrpcServerAuthzFilter final public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create(const ChannelArgs& args, - ChannelFilter::Args); + static absl::StatusOr> Create( + const ChannelArgs& args, ChannelFilter::Args); + + GrpcServerAuthzFilter( + RefCountedPtr auth_context, const ChannelArgs& args, + RefCountedPtr provider); class Call { public: @@ -52,10 +56,6 @@ class GrpcServerAuthzFilter final }; private: - GrpcServerAuthzFilter( - RefCountedPtr auth_context, const ChannelArgs& args, - RefCountedPtr provider); - bool IsAuthorized(ClientMetadata& initial_metadata); RefCountedPtr auth_context_; diff --git a/src/core/lib/security/certificate_provider/certificate_provider_factory.h b/src/core/lib/security/certificate_provider/certificate_provider_factory.h index beacb85032e..6d1b36e7b20 100644 --- a/src/core/lib/security/certificate_provider/certificate_provider_factory.h +++ b/src/core/lib/security/certificate_provider/certificate_provider_factory.h @@ -23,6 +23,7 @@ #include "absl/strings/string_view.h" +#include #include #include diff --git a/src/core/lib/security/context/security_context.cc b/src/core/lib/security/context/security_context.cc index 9cdc64bde6d..877adb8c788 100644 --- a/src/core/lib/security/context/security_context.cc +++ b/src/core/lib/security/context/security_context.cc @@ -22,6 +22,7 @@ #include +#include #include #include #include diff --git a/src/core/lib/security/context/security_context.h b/src/core/lib/security/context/security_context.h index bbc38020d4f..1c1b85bfc63 100644 --- a/src/core/lib/security/context/security_context.h +++ b/src/core/lib/security/context/security_context.h @@ -26,6 +26,7 @@ #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/alts/alts_credentials.h b/src/core/lib/security/credentials/alts/alts_credentials.h index 08ee0439666..46a513a0026 100644 --- a/src/core/lib/security/credentials/alts/alts_credentials.h +++ b/src/core/lib/security/credentials/alts/alts_credentials.h @@ -19,6 +19,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H #define GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H +#include #include #include #include diff --git a/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h b/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h index 6997beee5de..771beaf543a 100644 --- a/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h +++ b/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h @@ -19,6 +19,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_H #define GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_H +#include #include #include diff --git a/src/core/lib/security/credentials/call_creds_util.h b/src/core/lib/security/credentials/call_creds_util.h index 87dcc80fd76..6e95f100f94 100644 --- a/src/core/lib/security/credentials/call_creds_util.h +++ b/src/core/lib/security/credentials/call_creds_util.h @@ -19,6 +19,7 @@ #include +#include #include #include diff --git a/src/core/lib/security/credentials/channel_creds_registry_init.cc b/src/core/lib/security/credentials/channel_creds_registry_init.cc index 557967a54c7..4f19760f377 100644 --- a/src/core/lib/security/credentials/channel_creds_registry_init.cc +++ b/src/core/lib/security/credentials/channel_creds_registry_init.cc @@ -23,6 +23,7 @@ #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/composite/composite_credentials.h b/src/core/lib/security/credentials/composite/composite_credentials.h index 9c1841b311c..230706ed935 100644 --- a/src/core/lib/security/credentials/composite/composite_credentials.h +++ b/src/core/lib/security/credentials/composite/composite_credentials.h @@ -26,6 +26,7 @@ #include "absl/status/statusor.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/credentials.h b/src/core/lib/security/credentials/credentials.h index 59922c916b8..6a9661c05a6 100644 --- a/src/core/lib/security/credentials/credentials.h +++ b/src/core/lib/security/credentials/credentials.h @@ -26,6 +26,7 @@ #include "absl/status/statusor.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/external/aws_external_account_credentials.cc b/src/core/lib/security/credentials/external/aws_external_account_credentials.cc index 74609f44742..754fd4b3ed0 100644 --- a/src/core/lib/security/credentials/external/aws_external_account_credentials.cc +++ b/src/core/lib/security/credentials/external/aws_external_account_credentials.cc @@ -28,6 +28,7 @@ #include "absl/strings/string_view.h" #include "absl/types/optional.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/external/external_account_credentials.cc b/src/core/lib/security/credentials/external/external_account_credentials.cc index 9b027ae49b9..ae3f80e5986 100644 --- a/src/core/lib/security/credentials/external/external_account_credentials.cc +++ b/src/core/lib/security/credentials/external/external_account_credentials.cc @@ -35,6 +35,7 @@ #include "absl/time/clock.h" #include "absl/time/time.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/external/url_external_account_credentials.cc b/src/core/lib/security/credentials/external/url_external_account_credentials.cc index a010be13846..310c7e40170 100644 --- a/src/core/lib/security/credentials/external/url_external_account_credentials.cc +++ b/src/core/lib/security/credentials/external/url_external_account_credentials.cc @@ -27,6 +27,7 @@ #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/fake/fake_credentials.h b/src/core/lib/security/credentials/fake/fake_credentials.h index 8f6d4dfa11b..a18d90d0344 100644 --- a/src/core/lib/security/credentials/fake/fake_credentials.h +++ b/src/core/lib/security/credentials/fake/fake_credentials.h @@ -23,6 +23,7 @@ #include "absl/status/statusor.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/google_default/google_default_credentials.cc b/src/core/lib/security/credentials/google_default/google_default_credentials.cc index a8cc51d1f72..4291bdf5e62 100644 --- a/src/core/lib/security/credentials/google_default/google_default_credentials.cc +++ b/src/core/lib/security/credentials/google_default/google_default_credentials.cc @@ -28,7 +28,8 @@ #include "absl/strings/string_view.h" #include "absl/types/optional.h" -#include // IWYU pragma: keep +#include +#include #include #include #include diff --git a/src/core/lib/security/credentials/google_default/google_default_credentials.h b/src/core/lib/security/credentials/google_default/google_default_credentials.h index f17105bbdfa..acf2fa6404b 100644 --- a/src/core/lib/security/credentials/google_default/google_default_credentials.h +++ b/src/core/lib/security/credentials/google_default/google_default_credentials.h @@ -20,6 +20,7 @@ #define GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_GOOGLE_DEFAULT_GOOGLE_DEFAULT_CREDENTIALS_H #include +#include #include #include #include diff --git a/src/core/lib/security/credentials/iam/iam_credentials.h b/src/core/lib/security/credentials/iam/iam_credentials.h index ae2960e8466..e5ed10316dc 100644 --- a/src/core/lib/security/credentials/iam/iam_credentials.h +++ b/src/core/lib/security/credentials/iam/iam_credentials.h @@ -24,6 +24,7 @@ #include "absl/status/statusor.h" #include "absl/types/optional.h" +#include #include #include diff --git a/src/core/lib/security/credentials/insecure/insecure_credentials.h b/src/core/lib/security/credentials/insecure/insecure_credentials.h index 1ccee0bc480..e9bf9327e72 100644 --- a/src/core/lib/security/credentials/insecure/insecure_credentials.h +++ b/src/core/lib/security/credentials/insecure/insecure_credentials.h @@ -19,6 +19,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_INSECURE_INSECURE_CREDENTIALS_H #define GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_INSECURE_INSECURE_CREDENTIALS_H +#include #include #include #include diff --git a/src/core/lib/security/credentials/jwt/json_token.cc b/src/core/lib/security/credentials/jwt/json_token.cc index 82124dcd59c..ba81ab8dac3 100644 --- a/src/core/lib/security/credentials/jwt/json_token.cc +++ b/src/core/lib/security/credentials/jwt/json_token.cc @@ -33,6 +33,7 @@ #include "absl/status/statusor.h" #include "absl/strings/escaping.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/jwt/jwt_credentials.cc b/src/core/lib/security/credentials/jwt/jwt_credentials.cc index a5691cd2666..98c80150e94 100644 --- a/src/core/lib/security/credentials/jwt/jwt_credentials.cc +++ b/src/core/lib/security/credentials/jwt/jwt_credentials.cc @@ -27,6 +27,7 @@ #include "absl/status/status.h" #include "absl/strings/str_cat.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/jwt/jwt_credentials.h b/src/core/lib/security/credentials/jwt/jwt_credentials.h index 8ca6296f8ea..50df9094d0e 100644 --- a/src/core/lib/security/credentials/jwt/jwt_credentials.h +++ b/src/core/lib/security/credentials/jwt/jwt_credentials.h @@ -29,6 +29,7 @@ #include "absl/time/time.h" #include "absl/types/optional.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/local/local_credentials.h b/src/core/lib/security/credentials/local/local_credentials.h index 7a52d9a0d1e..77765bc6242 100644 --- a/src/core/lib/security/credentials/local/local_credentials.h +++ b/src/core/lib/security/credentials/local/local_credentials.h @@ -19,6 +19,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H #define GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H +#include #include #include #include diff --git a/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc b/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc index bbd666e7dd8..842b3f70f08 100644 --- a/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc +++ b/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc @@ -33,6 +33,7 @@ #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/oauth2/oauth2_credentials.h b/src/core/lib/security/credentials/oauth2/oauth2_credentials.h index 137818f095a..4bed299f406 100644 --- a/src/core/lib/security/credentials/oauth2/oauth2_credentials.h +++ b/src/core/lib/security/credentials/oauth2/oauth2_credentials.h @@ -26,6 +26,7 @@ #include "absl/status/statusor.h" #include "absl/types/optional.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/plugin/plugin_credentials.h b/src/core/lib/security/credentials/plugin/plugin_credentials.h index a3c22fbe278..715d071e14e 100644 --- a/src/core/lib/security/credentials/plugin/plugin_credentials.h +++ b/src/core/lib/security/credentials/plugin/plugin_credentials.h @@ -28,6 +28,7 @@ #include "absl/container/inlined_vector.h" #include "absl/status/statusor.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/ssl/ssl_credentials.h b/src/core/lib/security/credentials/ssl/ssl_credentials.h index 0dd131ff381..d76009f0666 100644 --- a/src/core/lib/security/credentials/ssl/ssl_credentials.h +++ b/src/core/lib/security/credentials/ssl/ssl_credentials.h @@ -20,6 +20,7 @@ #include +#include #include #include #include diff --git a/src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.cc b/src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.cc index 7744d62de1a..dbe28e1cf98 100644 --- a/src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.cc +++ b/src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.cc @@ -18,6 +18,7 @@ #include "absl/status/status.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/tls/grpc_tls_certificate_provider.cc b/src/core/lib/security/credentials/tls/grpc_tls_certificate_provider.cc index 5e81d3533bf..03921c540aa 100644 --- a/src/core/lib/security/credentials/tls/grpc_tls_certificate_provider.cc +++ b/src/core/lib/security/credentials/tls/grpc_tls_certificate_provider.cc @@ -25,6 +25,7 @@ #include "absl/status/status.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/tls/grpc_tls_certificate_verifier.h b/src/core/lib/security/credentials/tls/grpc_tls_certificate_verifier.h index 9734f191fc9..69a9861df22 100644 --- a/src/core/lib/security/credentials/tls/grpc_tls_certificate_verifier.h +++ b/src/core/lib/security/credentials/tls/grpc_tls_certificate_verifier.h @@ -23,6 +23,7 @@ #include "absl/base/thread_annotations.h" #include "absl/status/status.h" +#include #include #include #include diff --git a/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h b/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h index 6f56905ae32..b29468239a1 100644 --- a/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h +++ b/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h @@ -25,6 +25,7 @@ #include "absl/container/inlined_vector.h" +#include #include #include "src/core/lib/gprpp/ref_counted.h" diff --git a/src/core/lib/security/credentials/tls/tls_credentials.h b/src/core/lib/security/credentials/tls/tls_credentials.h index c79b4b0c554..c72dcd61da8 100644 --- a/src/core/lib/security/credentials/tls/tls_credentials.h +++ b/src/core/lib/security/credentials/tls/tls_credentials.h @@ -19,6 +19,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_TLS_TLS_CREDENTIALS_H #define GRPC_SRC_CORE_LIB_SECURITY_CREDENTIALS_TLS_TLS_CREDENTIALS_H +#include #include #include #include diff --git a/src/core/lib/security/credentials/xds/xds_credentials.h b/src/core/lib/security/credentials/xds/xds_credentials.h index b64def62b6f..09762d30276 100644 --- a/src/core/lib/security/credentials/xds/xds_credentials.h +++ b/src/core/lib/security/credentials/xds/xds_credentials.h @@ -28,6 +28,7 @@ #include "absl/status/status.h" +#include #include #include #include diff --git a/src/core/lib/security/security_connector/alts/alts_security_connector.h b/src/core/lib/security/security_connector/alts/alts_security_connector.h index 25cef39f92f..1f0c13a3618 100644 --- a/src/core/lib/security/security_connector/alts/alts_security_connector.h +++ b/src/core/lib/security/security_connector/alts/alts_security_connector.h @@ -18,6 +18,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H #define GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H +#include #include #include #include diff --git a/src/core/lib/security/security_connector/fake/fake_security_connector.h b/src/core/lib/security/security_connector/fake/fake_security_connector.h index a8823493750..1edc40c0b95 100644 --- a/src/core/lib/security/security_connector/fake/fake_security_connector.h +++ b/src/core/lib/security/security_connector/fake/fake_security_connector.h @@ -18,6 +18,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H #define GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H +#include #include #include #include diff --git a/src/core/lib/security/security_connector/insecure/insecure_security_connector.h b/src/core/lib/security/security_connector/insecure/insecure_security_connector.h index 8f78f610eab..c2716de0939 100644 --- a/src/core/lib/security/security_connector/insecure/insecure_security_connector.h +++ b/src/core/lib/security/security_connector/insecure/insecure_security_connector.h @@ -24,6 +24,7 @@ #include "absl/status/status.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/lib/security/security_connector/local/local_security_connector.h b/src/core/lib/security/security_connector/local/local_security_connector.h index ad39afbcf32..09020552f1c 100644 --- a/src/core/lib/security/security_connector/local/local_security_connector.h +++ b/src/core/lib/security/security_connector/local/local_security_connector.h @@ -18,6 +18,7 @@ #ifndef GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H #define GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H +#include #include #include #include diff --git a/src/core/lib/security/security_connector/security_connector.h b/src/core/lib/security/security_connector/security_connector.h index 1965984866b..f4bf841d042 100644 --- a/src/core/lib/security/security_connector/security_connector.h +++ b/src/core/lib/security/security_connector/security_connector.h @@ -24,6 +24,7 @@ #include "absl/status/status.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/src/core/lib/security/security_connector/ssl/ssl_security_connector.h b/src/core/lib/security/security_connector/ssl/ssl_security_connector.h index f743b6ff3b2..3ce665d587e 100644 --- a/src/core/lib/security/security_connector/ssl/ssl_security_connector.h +++ b/src/core/lib/security/security_connector/ssl/ssl_security_connector.h @@ -20,6 +20,7 @@ #define GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_SSL_SECURITY_CONNECTOR_H #include +#include #include #include #include diff --git a/src/core/lib/security/security_connector/ssl_utils.cc b/src/core/lib/security/security_connector/ssl_utils.cc index de302b6476c..41b89093833 100644 --- a/src/core/lib/security/security_connector/ssl_utils.cc +++ b/src/core/lib/security/security_connector/ssl_utils.cc @@ -29,6 +29,7 @@ #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" +#include #include #include #include diff --git a/src/core/lib/security/security_connector/tls/tls_security_connector.h b/src/core/lib/security/security_connector/tls/tls_security_connector.h index cf6593b4c68..c9293b39943 100644 --- a/src/core/lib/security/security_connector/tls/tls_security_connector.h +++ b/src/core/lib/security/security_connector/tls/tls_security_connector.h @@ -27,6 +27,7 @@ #include "absl/strings/string_view.h" #include "absl/types/optional.h" +#include #include #include #include diff --git a/src/core/lib/security/transport/auth_filters.h b/src/core/lib/security/transport/auth_filters.h index e4e80909526..06b8b6e6fae 100644 --- a/src/core/lib/security/transport/auth_filters.h +++ b/src/core/lib/security/transport/auth_filters.h @@ -21,6 +21,7 @@ #include "absl/status/statusor.h" +#include #include #include #include @@ -42,18 +43,18 @@ class ClientAuthFilter final : public ChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create(const ChannelArgs& args, - ChannelFilter::Args); + ClientAuthFilter( + RefCountedPtr security_connector, + RefCountedPtr auth_context); + + static absl::StatusOr> Create( + const ChannelArgs& args, ChannelFilter::Args); // Construct a promise for one call. ArenaPromise MakeCallPromise( CallArgs call_args, NextPromiseFactory next_promise_factory) override; private: - ClientAuthFilter( - RefCountedPtr security_connector, - RefCountedPtr auth_context); - ArenaPromise> GetCallCredsMetadata( CallArgs call_args); @@ -63,9 +64,6 @@ class ClientAuthFilter final : public ChannelFilter { class ServerAuthFilter final : public ImplementChannelFilter { private: - ServerAuthFilter(RefCountedPtr server_credentials, - RefCountedPtr auth_context); - class RunApplicationCode { public: RunApplicationCode(ServerAuthFilter* filter, ClientMetadata& metadata); @@ -98,8 +96,11 @@ class ServerAuthFilter final : public ImplementChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create(const ChannelArgs& args, - ChannelFilter::Args); + ServerAuthFilter(RefCountedPtr server_credentials, + RefCountedPtr auth_context); + + static absl::StatusOr> Create( + const ChannelArgs& args, ChannelFilter::Args); class Call { public: diff --git a/src/core/lib/security/transport/client_auth_filter.cc b/src/core/lib/security/transport/client_auth_filter.cc index 1840522e6c7..1314b7d523b 100644 --- a/src/core/lib/security/transport/client_auth_filter.cc +++ b/src/core/lib/security/transport/client_auth_filter.cc @@ -26,6 +26,7 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" +#include #include #include #include @@ -203,7 +204,7 @@ ArenaPromise ClientAuthFilter::MakeCallPromise( next_promise_factory); } -absl::StatusOr ClientAuthFilter::Create( +absl::StatusOr> ClientAuthFilter::Create( const ChannelArgs& args, ChannelFilter::Args) { auto* sc = args.GetObject(); if (sc == nullptr) { @@ -215,8 +216,9 @@ absl::StatusOr ClientAuthFilter::Create( return absl::InvalidArgumentError( "Auth context missing from client auth filter args"); } - return ClientAuthFilter(sc->RefAsSubclass(), - auth_context->Ref()); + return std::make_unique( + sc->RefAsSubclass(), + auth_context->Ref()); } const grpc_channel_filter ClientAuthFilter::kFilter = diff --git a/src/core/lib/security/transport/server_auth_filter.cc b/src/core/lib/security/transport/server_auth_filter.cc index 0354398684a..c36db059b3a 100644 --- a/src/core/lib/security/transport/server_auth_filter.cc +++ b/src/core/lib/security/transport/server_auth_filter.cc @@ -26,6 +26,7 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" +#include #include #include #include @@ -212,12 +213,13 @@ ServerAuthFilter::ServerAuthFilter( RefCountedPtr auth_context) : server_credentials_(server_credentials), auth_context_(auth_context) {} -absl::StatusOr ServerAuthFilter::Create( +absl::StatusOr> ServerAuthFilter::Create( const ChannelArgs& args, ChannelFilter::Args) { auto auth_context = args.GetObjectRef(); GPR_ASSERT(auth_context != nullptr); auto creds = args.GetObjectRef(); - return ServerAuthFilter(std::move(creds), std::move(auth_context)); + return std::make_unique(std::move(creds), + std::move(auth_context)); } } // namespace grpc_core diff --git a/src/core/lib/surface/call.cc b/src/core/lib/surface/call.cc index a8e026b0ece..08a3aeb02a5 100644 --- a/src/core/lib/surface/call.cc +++ b/src/core/lib/surface/call.cc @@ -2739,7 +2739,7 @@ class ClientPromiseBasedCall final : public PromiseBasedCall { ScopedContext context(this); args->channel->channel_stack()->stats_plugin_group->AddClientCallTracers( *args->path, args->registered_method, this->context()); - send_initial_metadata_ = GetContext()->MakePooled(); + send_initial_metadata_ = Arena::MakePooled(); send_initial_metadata_->Set(HttpPathMetadata(), std::move(*args->path)); if (args->authority.has_value()) { send_initial_metadata_->Set(HttpAuthorityMetadata(), @@ -2818,7 +2818,7 @@ class ClientPromiseBasedCall final : public PromiseBasedCall { } RefCountedPtr MakeCallSpine(CallArgs call_args) final { - class WrappingCallSpine final : public CallSpineInterface { + class WrappingCallSpine final : public PipeBasedCallSpine { public: WrappingCallSpine(ClientPromiseBasedCall* call, ClientMetadataHandle metadata) @@ -2859,14 +2859,14 @@ class ClientPromiseBasedCall final : public PromiseBasedCall { return call_->server_to_client_messages_; } - Pipe& server_trailing_metadata() override { - return server_trailing_metadata_; - } - Latch& cancel_latch() override { return cancel_error_; } + Latch& was_cancelled_latch() override { + return was_cancelled_latch_; + } + Party& party() override { return *call_; } Arena* arena() override { return call_->arena(); } @@ -2886,6 +2886,7 @@ class ClientPromiseBasedCall final : public PromiseBasedCall { Pipe client_initial_metadata_{call_->arena()}; Pipe server_trailing_metadata_{call_->arena()}; Latch cancel_error_; + Latch was_cancelled_latch_; }; GPR_ASSERT(call_args.server_initial_metadata == &server_initial_metadata_.sender); @@ -3700,11 +3701,12 @@ ServerPromiseBasedCall::MakeTopOfServerCallPromise( /////////////////////////////////////////////////////////////////////////////// // CallSpine based Server Call -class ServerCallSpine final : public CallSpineInterface, +class ServerCallSpine final : public PipeBasedCallSpine, public ServerCallContext, public BasicPromiseBasedCall { public: - ServerCallSpine(ServerInterface* server, Channel* channel, Arena* arena); + ServerCallSpine(ClientMetadataHandle client_initial_metadata, + ServerInterface* server, Channel* channel, Arena* arena); // CallSpineInterface Pipe& client_initial_metadata() override { @@ -3719,10 +3721,8 @@ class ServerCallSpine final : public CallSpineInterface, Pipe& server_to_client_messages() override { return server_to_client_messages_; } - Pipe& server_trailing_metadata() override { - return server_trailing_metadata_; - } Latch& cancel_latch() override { return cancel_latch_; } + Latch& was_cancelled_latch() override { return was_cancelled_latch_; } Party& party() override { return *this; } Arena* arena() override { return BasicPromiseBasedCall::arena(); } void IncrementRefCount() override { InternalRef("CallSpine"); } @@ -3735,7 +3735,9 @@ class ServerCallSpine final : public CallSpineInterface, } void CancelWithError(grpc_error_handle error) override { SpawnInfallible("CancelWithError", [this, error = std::move(error)] { - std::ignore = Cancel(ServerMetadataFromStatus(error)); + auto status = ServerMetadataFromStatus(error); + status->Set(GrpcCallWasCancelled(), true); + PushServerTrailingMetadata(std::move(status)); return Empty{}; }); } @@ -3784,15 +3786,15 @@ class ServerCallSpine final : public CallSpineInterface, Pipe client_to_server_messages_; // Messages travelling from the transport to the application. Pipe server_to_client_messages_; - // Trailing metadata from server to client - Pipe server_trailing_metadata_; // Latch that can be set to terminate the call Latch cancel_latch_; + Latch was_cancelled_latch_; grpc_byte_buffer** recv_message_ = nullptr; ClientMetadataHandle client_initial_metadata_stored_; }; -ServerCallSpine::ServerCallSpine(ServerInterface* server, Channel* channel, +ServerCallSpine::ServerCallSpine(ClientMetadataHandle client_initial_metadata, + ServerInterface* server, Channel* channel, Arena* arena) : BasicPromiseBasedCall(arena, 0, 1, [channel, server]() -> grpc_call_create_args { @@ -3811,11 +3813,15 @@ ServerCallSpine::ServerCallSpine(ServerInterface* server, Channel* channel, client_initial_metadata_(arena), server_initial_metadata_(arena), client_to_server_messages_(arena), - server_to_client_messages_(arena), - server_trailing_metadata_(arena) { + server_to_client_messages_(arena) { global_stats().IncrementServerCallsCreated(); ScopedContext ctx(this); channel->channel_stack()->InitServerCallSpine(this); + SpawnGuarded("push_client_initial_metadata", + [this, md = std::move(client_initial_metadata)]() mutable { + return Map(client_initial_metadata_.sender.Push(std::move(md)), + [](bool r) { return StatusFlag(r); }); + }); } void ServerCallSpine::PublishInitialMetadata( @@ -4081,10 +4087,15 @@ void ServerCallSpine::CommitBatch(const grpc_op* ops, size_t nops, metadata->Set(GrpcMessageMetadata(), Slice(grpc_slice_copy(*details))); } + GPR_ASSERT(metadata != nullptr); return [this, metadata = std::move(metadata)]() mutable { - server_to_client_messages_.sender.Close(); - return Map(server_trailing_metadata_.sender.Push(std::move(metadata)), - [](bool r) { return StatusFlag(r); }); + GPR_ASSERT(metadata != nullptr); + return [this, + metadata = std::move(metadata)]() mutable -> Poll { + GPR_ASSERT(metadata != nullptr); + PushServerTrailingMetadata(std::move(metadata)); + return Success{}; + }; }; }); auto recv_message = @@ -4099,13 +4110,15 @@ void ServerCallSpine::CommitBatch(const grpc_op* ops, size_t nops, }; }); auto primary_ops = AllOk( - std::move(send_initial_metadata), std::move(send_message), - std::move(send_trailing_metadata), std::move(recv_message)); + TrySeq(AllOk(std::move(send_initial_metadata), + std::move(send_message)), + std::move(send_trailing_metadata)), + std::move(recv_message)); if (got_ops[GRPC_OP_RECV_CLOSE_ON_SERVER] != 255) { auto recv_trailing_metadata = MaybeOp( ops, got_ops[GRPC_OP_RECV_CLOSE_ON_SERVER], [this](const grpc_op& op) { return [this, cancelled = op.data.recv_close_on_server.cancelled]() { - return Map(server_trailing_metadata_.receiver.AwaitClosed(), + return Map(WasCancelled(), [cancelled, this](bool result) -> Success { ResetDeadline(); *cancelled = result ? 1 : 0; @@ -4141,14 +4154,15 @@ void ServerCallSpine::CommitBatch(const grpc_op* ops, size_t nops, } } -RefCountedPtr MakeServerCall(ServerInterface* server, - Channel* channel, - Arena* arena) { - return RefCountedPtr( - arena->New(server, channel, arena)); +RefCountedPtr MakeServerCall( + ClientMetadataHandle client_initial_metadata, ServerInterface* server, + Channel* channel, Arena* arena) { + return RefCountedPtr(arena->New( + std::move(client_initial_metadata), server, channel, arena)); } #else -RefCountedPtr MakeServerCall(ServerInterface*, Channel*, +RefCountedPtr MakeServerCall(ClientMetadataHandle, + ServerInterface*, Channel*, Arena*) { Crash("not implemented"); } diff --git a/src/core/lib/surface/call.h b/src/core/lib/surface/call.h index 32aba4c3c60..ddc29ed878a 100644 --- a/src/core/lib/surface/call.h +++ b/src/core/lib/surface/call.h @@ -158,9 +158,10 @@ class CallContext { template <> struct ContextType {}; -RefCountedPtr MakeServerCall(ServerInterface* server, - Channel* channel, - Arena* arena); +// TODO(ctiller): remove once call-v3 finalized +RefCountedPtr MakeServerCall( + ClientMetadataHandle client_initial_metadata, ServerInterface* server, + Channel* channel, Arena* arena); } // namespace grpc_core diff --git a/src/core/lib/surface/channel_init.h b/src/core/lib/surface/channel_init.h index 48de857f76d..5f1bacdeff1 100644 --- a/src/core/lib/surface/channel_init.h +++ b/src/core/lib/surface/channel_init.h @@ -285,6 +285,11 @@ class ChannelInit { grpc_channel_stack_type type, const ChannelArgs& args) const; private: + // The type of object returned by a filter's Create method. + template + using CreatedType = + typename decltype(T::Create(ChannelArgs(), {}))::value_type; + struct Filter { Filter(const grpc_channel_filter* filter, const ChannelFilterVtable* vtable, std::vector predicates, bool skip_v3, @@ -328,17 +333,17 @@ class ChannelInit { template const ChannelInit::ChannelFilterVtable ChannelInit::VtableForType>::kVtable = { - sizeof(T), alignof(T), + sizeof(CreatedType), alignof(CreatedType), [](void* data, const ChannelArgs& args) -> absl::Status { // TODO(ctiller): fill in ChannelFilter::Args (2nd arg) - absl::StatusOr r = T::Create(args, {}); + absl::StatusOr> r = T::Create(args, {}); if (!r.ok()) return r.status(); - new (data) T(std::move(*r)); + new (data) CreatedType(std::move(*r)); return absl::OkStatus(); }, - [](void* data) { static_cast(data)->~T(); }, + [](void* data) { Destruct(static_cast*>(data)); }, [](void* data, CallFilters::StackBuilder& builder) { - builder.Add(static_cast(data)); + builder.Add(static_cast*>(data)->get()); }}; } // namespace grpc_core diff --git a/src/core/lib/surface/lame_client.cc b/src/core/lib/surface/lame_client.cc index ce8a4ea1880..8966f34ebf7 100644 --- a/src/core/lib/surface/lame_client.cc +++ b/src/core/lib/surface/lame_client.cc @@ -59,17 +59,15 @@ const grpc_channel_filter LameClientFilter::kFilter = MakePromiseBasedFilter("lame-client"); -absl::StatusOr LameClientFilter::Create( +absl::StatusOr> LameClientFilter::Create( const ChannelArgs& args, ChannelFilter::Args) { - return LameClientFilter( + return std::make_unique( *args.GetPointer(GRPC_ARG_LAME_FILTER_ERROR)); } LameClientFilter::LameClientFilter(absl::Status error) - : error_(std::move(error)), state_(std::make_unique()) {} - -LameClientFilter::State::State() - : state_tracker("lame_client", GRPC_CHANNEL_SHUTDOWN) {} + : error_(std::move(error)), + state_tracker_("lame_client", GRPC_CHANNEL_SHUTDOWN) {} ArenaPromise LameClientFilter::MakeCallPromise( CallArgs args, NextPromiseFactory) { @@ -92,13 +90,13 @@ bool LameClientFilter::GetChannelInfo(const grpc_channel_info*) { return true; } bool LameClientFilter::StartTransportOp(grpc_transport_op* op) { { - MutexLock lock(&state_->mu); + MutexLock lock(&mu_); if (op->start_connectivity_watch != nullptr) { - state_->state_tracker.AddWatcher(op->start_connectivity_watch_state, - std::move(op->start_connectivity_watch)); + state_tracker_.AddWatcher(op->start_connectivity_watch_state, + std::move(op->start_connectivity_watch)); } if (op->stop_connectivity_watch != nullptr) { - state_->state_tracker.RemoveWatcher(op->stop_connectivity_watch); + state_tracker_.RemoveWatcher(op->stop_connectivity_watch); } } if (op->send_ping.on_initiate != nullptr) { diff --git a/src/core/lib/surface/lame_client.h b/src/core/lib/surface/lame_client.h index a8464fc9b96..1f8d323d352 100644 --- a/src/core/lib/surface/lame_client.h +++ b/src/core/lib/surface/lame_client.h @@ -47,7 +47,9 @@ class LameClientFilter : public ChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + explicit LameClientFilter(absl::Status error); + + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); ArenaPromise MakeCallPromise( CallArgs call_args, NextPromiseFactory next_promise_factory) override; @@ -55,15 +57,9 @@ class LameClientFilter : public ChannelFilter { bool GetChannelInfo(const grpc_channel_info*) override; private: - explicit LameClientFilter(absl::Status error); - absl::Status error_; - struct State { - State(); - Mutex mu; - ConnectivityStateTracker state_tracker ABSL_GUARDED_BY(mu); - }; - std::unique_ptr state_; + Mutex mu_; + ConnectivityStateTracker state_tracker_ ABSL_GUARDED_BY(mu_); }; extern const grpc_arg_pointer_vtable kLameFilterErrorArgVtable; diff --git a/src/core/lib/surface/server.cc b/src/core/lib/surface/server.cc index 7b5fb2b95f9..5e974ec25a6 100644 --- a/src/core/lib/surface/server.cc +++ b/src/core/lib/surface/server.cc @@ -232,7 +232,8 @@ struct Server::RequestedCall { data.registered.optional_payload = optional_payload; } - void Complete(NextResult payload, ClientMetadata& md) { + template + void Complete(OptionalPayload payload, ClientMetadata& md) { Timestamp deadline = GetContext()->deadline(); switch (type) { case RequestedCall::Type::BATCH_CALL: @@ -1301,9 +1302,10 @@ Server::ChannelData::~ChannelData() { Arena* Server::ChannelData::CreateArena() { return channel_->CreateArena(); } absl::StatusOr Server::ChannelData::CreateCall( - ClientMetadata& client_initial_metadata, Arena* arena) { - SetRegisteredMethodOnMetadata(client_initial_metadata); - auto call = MakeServerCall(server_.get(), channel_.get(), arena); + ClientMetadataHandle client_initial_metadata, Arena* arena) { + SetRegisteredMethodOnMetadata(*client_initial_metadata); + auto call = MakeServerCall(std::move(client_initial_metadata), server_.get(), + channel_.get(), arena); InitCall(call); return CallInitiator(std::move(call)); } @@ -1427,10 +1429,10 @@ void Server::ChannelData::InitCall(RefCountedPtr call) { call->SpawnGuarded("request_matcher", [this, call]() { return TrySeq( // Wait for initial metadata to pass through all filters - Map(call->client_initial_metadata().receiver.Next(), - [](NextResult md) + Map(call->PullClientInitialMetadata(), + [](ValueOrFailure md) -> absl::StatusOr { - if (!md.has_value()) { + if (!md.ok()) { return absl::InternalError("Missing metadata"); } if (!md.value()->get_pointer(HttpPathMetadata())) { @@ -1456,24 +1458,19 @@ void Server::ChannelData::InitCall(RefCountedPtr call) { } auto maybe_read_first_message = If( payload_handling == GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER, - [call]() { - return call->client_to_server_messages().receiver.Next(); - }, - []() -> NextResult { - return NextResult(); + [call]() { return call->PullClientToServerMessage(); }, + []() -> ValueOrFailure> { + return ValueOrFailure>( + absl::nullopt); }); return TryJoin( - Map(std::move(maybe_read_first_message), - [](NextResult n) { - return ValueOrFailure>{ - std::move(n)}; - }), - rm->MatchRequest(cq_idx()), [md = std::move(md)]() mutable { + std::move(maybe_read_first_message), rm->MatchRequest(cq_idx()), + [md = std::move(md)]() mutable { return ValueOrFailure(std::move(md)); }); }, // Publish call to cq - [](std::tuple, + [](std::tuple, RequestMatcherInterface::MatchResult, ClientMetadataHandle> r) { diff --git a/src/core/lib/surface/server.h b/src/core/lib/surface/server.h index 6e80b96445f..66f7b6683e0 100644 --- a/src/core/lib/surface/server.h +++ b/src/core/lib/surface/server.h @@ -39,6 +39,7 @@ #include "absl/types/optional.h" #include +#include #include #include #include @@ -74,6 +75,9 @@ "grpc.server.max_pending_requests_hard_limit" namespace grpc_core { +namespace experimental { +class PassiveListenerImpl; +} // namespace experimental extern TraceFlag grpc_server_channel_trace; @@ -112,7 +116,7 @@ class Server : public ServerInterface, /// Interface for listeners. /// Implementations must override the Orphan() method, which should stop /// listening and initiate destruction of the listener. - class ListenerInterface : public Orphanable { + class ListenerInterface : public InternallyRefCounted { public: ~ListenerInterface() override = default; @@ -212,6 +216,14 @@ class Server : public ServerInterface, void SendGoaways() ABSL_LOCKS_EXCLUDED(mu_global_, mu_call_); private: + // note: the grpc_core::Server redundant namespace qualification is + // required for older gcc versions. + // TODO(yashykt): eliminate this friend statement as part of your upcoming + // server listener refactoring. + friend absl::Status(::grpc_server_add_passive_listener)( + grpc_core::Server* server, grpc_server_credentials* credentials, + std::shared_ptr + passive_listener); struct RequestedCall; class RequestMatcherInterface; @@ -246,7 +258,7 @@ class Server : public ServerInterface, Arena* CreateArena() override; absl::StatusOr CreateCall( - ClientMetadata& client_initial_metadata, Arena* arena) override; + ClientMetadataHandle client_initial_metadata, Arena* arena) override; private: class ConnectivityWatcher; diff --git a/src/core/lib/transport/batch_builder.h b/src/core/lib/transport/batch_builder.h index ee032df12db..68a65ba25be 100644 --- a/src/core/lib/transport/batch_builder.h +++ b/src/core/lib/transport/batch_builder.h @@ -147,8 +147,7 @@ class BatchBuilder { absl::string_view name() const override { return "receive_message"; } MessageHandle IntoMessageHandle() { - return GetContext()->MakePooled(std::move(*payload), - flags); + return Arena::MakePooled(std::move(*payload), flags); } absl::optional payload; @@ -161,7 +160,7 @@ class BatchBuilder { using PendingCompletion::PendingCompletion; Arena::PoolPtr metadata = - GetContext()->MakePooled(); + Arena::MakePooled(); protected: ~PendingReceiveMetadata() = default; @@ -328,7 +327,7 @@ inline auto BatchBuilder::SendClientTrailingMetadata(Target target) { auto* pc = batch->GetInitializedCompletion(&Batch::pending_sends); batch->batch.on_complete = &pc->on_done_closure; batch->batch.send_trailing_metadata = true; - auto metadata = GetContext()->MakePooled(); + auto metadata = Arena::MakePooled(); payload_->send_trailing_metadata.send_trailing_metadata = metadata.get(); payload_->send_trailing_metadata.sent = nullptr; pc->send_trailing_metadata = std::move(metadata); diff --git a/src/core/lib/transport/call_spine.cc b/src/core/lib/transport/call_spine.cc index 0edcc3d335b..6b8ce59916e 100644 --- a/src/core/lib/transport/call_spine.cc +++ b/src/core/lib/transport/call_spine.cc @@ -18,16 +18,7 @@ namespace grpc_core { -void ForwardCall(CallHandler call_handler, CallInitiator call_initiator, - ClientMetadataHandle client_initial_metadata) { - // Send initial metadata. - call_initiator.SpawnGuarded( - "send_initial_metadata", - [client_initial_metadata = std::move(client_initial_metadata), - call_initiator]() mutable { - return call_initiator.PushClientInitialMetadata( - std::move(client_initial_metadata)); - }); +void ForwardCall(CallHandler call_handler, CallInitiator call_initiator) { // Read messages from handler into initiator. call_handler.SpawnGuarded("read_messages", [call_handler, call_initiator]() mutable { @@ -88,10 +79,10 @@ void ForwardCall(CallHandler call_handler, CallInitiator call_initiator, })), call_initiator.PullServerTrailingMetadata(), [call_handler](ServerMetadataHandle md) mutable { - call_handler.SpawnGuarded( - "recv_trailing_metadata", - [md = std::move(md), call_handler]() mutable { - return call_handler.PushServerTrailingMetadata(std::move(md)); + call_handler.SpawnInfallible( + "recv_trailing", [call_handler, md = std::move(md)]() mutable { + call_handler.PushServerTrailingMetadata(std::move(md)); + return Empty{}; }); return Empty{}; }); @@ -99,9 +90,12 @@ void ForwardCall(CallHandler call_handler, CallInitiator call_initiator, } CallInitiatorAndHandler MakeCall( - grpc_event_engine::experimental::EventEngine* event_engine, Arena* arena) { - auto spine = CallSpine::Create(event_engine, arena); - return {CallInitiator(spine), CallHandler(spine)}; + ClientMetadataHandle client_initial_metadata, + grpc_event_engine::experimental::EventEngine* event_engine, Arena* arena, + bool is_arena_owned) { + auto spine = CallSpine::Create(std::move(client_initial_metadata), + event_engine, arena, is_arena_owned); + return {CallInitiator(spine), UnstartedCallHandler(spine)}; } } // namespace grpc_core diff --git a/src/core/lib/transport/call_spine.h b/src/core/lib/transport/call_spine.h index 31381ef9f83..514c92c245d 100644 --- a/src/core/lib/transport/call_spine.h +++ b/src/core/lib/transport/call_spine.h @@ -25,6 +25,7 @@ #include "src/core/lib/promise/party.h" #include "src/core/lib/promise/pipe.h" #include "src/core/lib/promise/prioritized_race.h" +#include "src/core/lib/promise/promise.h" #include "src/core/lib/promise/status_flag.h" #include "src/core/lib/promise/try_seq.h" #include "src/core/lib/transport/message.h" @@ -42,12 +43,6 @@ namespace grpc_core { class CallSpineInterface { public: virtual ~CallSpineInterface() = default; - virtual Pipe& client_initial_metadata() = 0; - virtual Pipe& server_initial_metadata() = 0; - virtual Pipe& client_to_server_messages() = 0; - virtual Pipe& server_to_client_messages() = 0; - virtual Pipe& server_trailing_metadata() = 0; - virtual Latch& cancel_latch() = 0; // Add a callback to be called when server trailing metadata is received. void OnDone(absl::AnyInvocable fn) { if (on_done_ == nullptr) { @@ -67,33 +62,24 @@ class CallSpineInterface { virtual void IncrementRefCount() = 0; virtual void Unref() = 0; - // Cancel the call with the given metadata. - // Regarding the `MUST_USE_RESULT absl::nullopt_t`: - // Most cancellation calls right now happen in pipe interceptors; - // there `nullopt` indicates terminate processing of this pipe and close with - // error. - // It's convenient then to have the Cancel operation (setting the latch to - // terminate the call) be the last thing that occurs in a pipe interceptor, - // and this construction supports that (and has helped the author not write - // some bugs). - GRPC_MUST_USE_RESULT absl::nullopt_t Cancel(ServerMetadataHandle metadata) { - GPR_DEBUG_ASSERT(GetContext() == &party()); - auto& c = cancel_latch(); - if (c.is_set()) return absl::nullopt; - c.Set(std::move(metadata)); - CallOnDone(); - client_initial_metadata().sender.CloseWithError(); - server_initial_metadata().sender.CloseWithError(); - client_to_server_messages().sender.CloseWithError(); - server_to_client_messages().sender.CloseWithError(); - server_trailing_metadata().sender.CloseWithError(); - return absl::nullopt; - } - - auto WaitForCancel() { - GPR_DEBUG_ASSERT(GetContext() == &party()); - return cancel_latch().Wait(); - } + virtual Promise>> + PullServerInitialMetadata() = 0; + virtual Promise PullServerTrailingMetadata() = 0; + virtual Promise PushClientToServerMessage( + MessageHandle message) = 0; + virtual Promise>> + PullClientToServerMessage() = 0; + virtual Promise PushServerToClientMessage( + MessageHandle message) = 0; + virtual Promise>> + PullServerToClientMessage() = 0; + virtual void PushServerTrailingMetadata(ServerMetadataHandle md) = 0; + virtual void FinishSends() = 0; + virtual Promise> + PullClientInitialMetadata() = 0; + virtual Promise PushServerInitialMetadata( + absl::optional md) = 0; + virtual Promise WasCancelled() = 0; // Wrap a promise so that if it returns failure it automatically cancels // the rest of the call. @@ -105,7 +91,7 @@ class CallSpineInterface { using ResultType = typename P::Result; return Map(std::move(promise), [this](ResultType r) { if (!IsStatusOk(r)) { - std::ignore = Cancel(StatusCast(r)); + PushServerTrailingMetadata(StatusCast(r)); } return r; }); @@ -121,7 +107,8 @@ class CallSpineInterface { // Spawn a promise that returns some status-like type; if the status // represents failure automatically cancel the rest of the call. template - void SpawnGuarded(absl::string_view name, PromiseFactory promise_factory) { + void SpawnGuarded(absl::string_view name, PromiseFactory promise_factory, + DebugLocation whence = {}) { using FactoryType = promise_detail::OncePromiseFactory; using PromiseType = typename FactoryType::Promise; @@ -130,27 +117,158 @@ class CallSpineInterface { std::is_same()))>::value, "SpawnGuarded promise must return a status-like object"); - party().Spawn(name, std::move(promise_factory), [this](ResultType r) { - if (!IsStatusOk(r)) { - if (grpc_trace_promise_primitives.enabled()) { - gpr_log(GPR_DEBUG, "SpawnGuarded sees failure: %s", - r.ToString().c_str()); - } - std::ignore = Cancel(StatusCast(std::move(r))); - } - }); + party().Spawn( + name, std::move(promise_factory), [this, whence](ResultType r) { + if (!IsStatusOk(r)) { + if (grpc_trace_promise_primitives.enabled()) { + gpr_log(GPR_INFO, "SpawnGuarded sees failure: %s (source: %s:%d)", + r.ToString().c_str(), whence.file(), whence.line()); + } + auto status = StatusCast(std::move(r)); + status->Set(GrpcCallWasCancelled(), true); + PushServerTrailingMetadata(std::move(status)); + } + }); } private: absl::AnyInvocable on_done_{nullptr}; }; -class CallSpine final : public CallSpineInterface, public Party { +// Implementation of CallSpine atop the v2 Pipe based arrangement. +// This implementation will go away in favor of an implementation atop +// CallFilters by the time v3 lands. +class PipeBasedCallSpine : public CallSpineInterface { + public: + virtual Pipe& client_initial_metadata() = 0; + virtual Pipe& server_initial_metadata() = 0; + virtual Pipe& client_to_server_messages() = 0; + virtual Pipe& server_to_client_messages() = 0; + virtual Latch& cancel_latch() = 0; + virtual Latch& was_cancelled_latch() = 0; + + Promise>> + PullServerInitialMetadata() final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return Map(server_initial_metadata().receiver.Next(), + [](NextResult md) + -> ValueOrFailure> { + if (!md.has_value()) { + if (md.cancelled()) return Failure{}; + return absl::optional(); + } + return absl::optional(std::move(*md)); + }); + } + + Promise PullServerTrailingMetadata() final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return cancel_latch().Wait(); + } + + Promise>> + PullServerToClientMessage() final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return Map(server_to_client_messages().receiver.Next(), MapNextMessage); + } + + Promise PushClientToServerMessage(MessageHandle message) final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return Map(client_to_server_messages().sender.Push(std::move(message)), + [](bool r) { return StatusFlag(r); }); + } + + Promise>> + PullClientToServerMessage() final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return Map(client_to_server_messages().receiver.Next(), MapNextMessage); + } + + Promise PushServerToClientMessage(MessageHandle message) final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return Map(server_to_client_messages().sender.Push(std::move(message)), + [](bool r) { return StatusFlag(r); }); + } + + void FinishSends() final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + client_to_server_messages().sender.Close(); + } + + void PushServerTrailingMetadata(ServerMetadataHandle metadata) final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + auto& c = cancel_latch(); + if (c.is_set()) return; + const bool was_cancelled = + metadata->get(GrpcCallWasCancelled()).value_or(false); + c.Set(std::move(metadata)); + CallOnDone(); + was_cancelled_latch().Set(was_cancelled); + client_initial_metadata().sender.CloseWithError(); + server_initial_metadata().sender.Close(); + client_to_server_messages().sender.CloseWithError(); + server_to_client_messages().sender.Close(); + } + + Promise WasCancelled() final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return was_cancelled_latch().Wait(); + } + + Promise> PullClientInitialMetadata() + final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return Map(client_initial_metadata().receiver.Next(), + [](NextResult md) + -> ValueOrFailure { + if (!md.has_value()) return Failure{}; + return std::move(*md); + }); + } + + Promise PushServerInitialMetadata( + absl::optional md) final { + GPR_DEBUG_ASSERT(GetContext() == &party()); + return If( + md.has_value(), + [&md, this]() { + return Map(server_initial_metadata().sender.Push(std::move(*md)), + [](bool ok) { return StatusFlag(ok); }); + }, + [this]() { + server_initial_metadata().sender.Close(); + return []() -> StatusFlag { return Success{}; }; + }); + } + + private: + static ValueOrFailure> MapNextMessage( + NextResult r) { + if (!r.has_value()) { + if (r.cancelled()) return Failure{}; + return absl::optional(); + } + return absl::optional(std::move(*r)); + } +}; + +class CallSpine final : public PipeBasedCallSpine, public Party { public: static RefCountedPtr Create( - grpc_event_engine::experimental::EventEngine* event_engine, - Arena* arena) { - return RefCountedPtr(arena->New(event_engine, arena)); + ClientMetadataHandle client_initial_metadata, + grpc_event_engine::experimental::EventEngine* event_engine, Arena* arena, + bool is_arena_owned) { + auto spine = RefCountedPtr( + arena->New(event_engine, arena, is_arena_owned)); + spine->SpawnInfallible( + "push_client_initial_metadata", + [spine = spine.get(), client_initial_metadata = std::move( + client_initial_metadata)]() mutable { + return Map(spine->client_initial_metadata_.sender.Push( + std::move(client_initial_metadata)), + [](bool) { return Empty{}; }); + }); + return spine; } Pipe& client_initial_metadata() override { @@ -165,10 +283,8 @@ class CallSpine final : public CallSpineInterface, public Party { Pipe& server_to_client_messages() override { return server_to_client_messages_; } - Pipe& server_trailing_metadata() override { - return server_trailing_metadata_; - } Latch& cancel_latch() override { return cancel_latch_; } + Latch& was_cancelled_latch() override { return was_cancelled_latch_; } Party& party() override { return *this; } Arena* arena() override { return arena_; } void IncrementRefCount() override { Party::IncrementRefCount(); } @@ -177,8 +293,11 @@ class CallSpine final : public CallSpineInterface, public Party { private: friend class Arena; CallSpine(grpc_event_engine::experimental::EventEngine* event_engine, - Arena* arena) - : Party(1), arena_(arena), event_engine_(event_engine) {} + Arena* arena, bool is_arena_owned) + : Party(1), + arena_(arena), + is_arena_owned_(is_arena_owned), + event_engine_(event_engine) {} class ScopedContext : public ScopedActivity, public promise_detail::Context { @@ -208,6 +327,7 @@ class CallSpine final : public CallSpineInterface, public Party { } Arena* arena_; + bool is_arena_owned_; // Initial metadata from client to server Pipe client_initial_metadata_{arena()}; // Initial metadata from server to client @@ -216,10 +336,9 @@ class CallSpine final : public CallSpineInterface, public Party { Pipe client_to_server_messages_{arena()}; // Messages travelling from the transport to the application. Pipe server_to_client_messages_{arena()}; - // Trailing metadata from server to client - Pipe server_trailing_metadata_{arena()}; // Latch that can be set to terminate the call Latch cancel_latch_; + Latch was_cancelled_latch_; // Event engine associated with this call grpc_event_engine::experimental::EventEngine* const event_engine_; }; @@ -229,73 +348,31 @@ class CallInitiator { explicit CallInitiator(RefCountedPtr spine) : spine_(std::move(spine)) {} - auto PushClientInitialMetadata(ClientMetadataHandle md) { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return Map(spine_->client_initial_metadata().sender.Push(std::move(md)), - [](bool ok) { return StatusFlag(ok); }); + template + auto CancelIfFails(Promise promise) { + return spine_->CancelIfFails(std::move(promise)); } auto PullServerInitialMetadata() { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return Map(spine_->server_initial_metadata().receiver.Next(), - [](NextResult md) - -> ValueOrFailure> { - if (!md.has_value()) { - if (md.cancelled()) return Failure{}; - return absl::optional(); - } - return absl::optional(std::move(*md)); - }); - } - - auto PullServerTrailingMetadata() { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return PrioritizedRace( - Seq(spine_->server_trailing_metadata().receiver.Next(), - [spine = spine_](NextResult md) mutable { - return [md = std::move(md), - spine]() mutable -> Poll { - // If the pipe was closed at cancellation time, we'll see no - // value here. Return pending and allow the cancellation to win - // the race. - if (!md.has_value()) return Pending{}; - spine->server_trailing_metadata().sender.Close(); - return std::move(*md); - }; - }), - Map(spine_->WaitForCancel(), - [spine = spine_](ServerMetadataHandle md) -> ServerMetadataHandle { - spine->server_trailing_metadata().sender.CloseWithError(); - return md; - })); - } - - auto PullMessage() { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return spine_->server_to_client_messages().receiver.Next(); + return spine_->PullServerInitialMetadata(); } auto PushMessage(MessageHandle message) { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return Map( - spine_->client_to_server_messages().sender.Push(std::move(message)), - [](bool r) { return StatusFlag(r); }); + return spine_->PushClientToServerMessage(std::move(message)); } - void FinishSends() { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - spine_->client_to_server_messages().sender.Close(); - } + void FinishSends() { spine_->FinishSends(); } - template - auto CancelIfFails(Promise promise) { - return spine_->CancelIfFails(std::move(promise)); + auto PullMessage() { return spine_->PullServerToClientMessage(); } + + auto PullServerTrailingMetadata() { + return spine_->PullServerTrailingMetadata(); } void Cancel() { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - std::ignore = - spine_->Cancel(ServerMetadataFromStatus(absl::CancelledError())); + auto status = ServerMetadataFromStatus(absl::CancelledError()); + status->Set(GrpcCallWasCancelled(), true); + spine_->PushServerTrailingMetadata(std::move(status)); } void OnDone(absl::AnyInvocable fn) { spine_->OnDone(std::move(fn)); } @@ -327,55 +404,59 @@ class CallHandler { : spine_(std::move(spine)) {} auto PullClientInitialMetadata() { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return Map(spine_->client_initial_metadata().receiver.Next(), - [](NextResult md) - -> ValueOrFailure { - if (!md.has_value()) return Failure{}; - return std::move(*md); - }); + return spine_->PullClientInitialMetadata(); } auto PushServerInitialMetadata(absl::optional md) { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return If( - md.has_value(), - [&md, this]() { - return Map( - spine_->server_initial_metadata().sender.Push(std::move(*md)), - [](bool ok) { return StatusFlag(ok); }); - }, - [this]() { - spine_->server_initial_metadata().sender.Close(); - return []() -> StatusFlag { return Success{}; }; - }); + return spine_->PushServerInitialMetadata(std::move(md)); } - auto PushServerTrailingMetadata(ServerMetadataHandle md) { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - spine_->server_initial_metadata().sender.Close(); - spine_->server_to_client_messages().sender.Close(); - spine_->client_to_server_messages().receiver.CloseWithError(); - spine_->CallOnDone(); - return Map(spine_->server_trailing_metadata().sender.Push(std::move(md)), - [](bool ok) { return StatusFlag(ok); }); + void PushServerTrailingMetadata(ServerMetadataHandle status) { + spine_->PushServerTrailingMetadata(std::move(status)); } - auto PullMessage() { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return spine_->client_to_server_messages().receiver.Next(); + void OnDone(absl::AnyInvocable fn) { spine_->OnDone(std::move(fn)); } + + template + auto CancelIfFails(Promise promise) { + return spine_->CancelIfFails(std::move(promise)); } auto PushMessage(MessageHandle message) { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - return Map( - spine_->server_to_client_messages().sender.Push(std::move(message)), - [](bool ok) { return StatusFlag(ok); }); + return spine_->PushServerToClientMessage(std::move(message)); + } + + auto PullMessage() { return spine_->PullClientToServerMessage(); } + + template + void SpawnGuarded(absl::string_view name, PromiseFactory promise_factory, + DebugLocation whence = {}) { + spine_->SpawnGuarded(name, std::move(promise_factory), whence); } - void Cancel(ServerMetadataHandle status) { - GPR_DEBUG_ASSERT(GetContext() == &spine_->party()); - std::ignore = spine_->Cancel(std::move(status)); + template + void SpawnInfallible(absl::string_view name, PromiseFactory promise_factory) { + spine_->SpawnInfallible(name, std::move(promise_factory)); + } + + template + auto SpawnWaitable(absl::string_view name, PromiseFactory promise_factory) { + return spine_->party().SpawnWaitable(name, std::move(promise_factory)); + } + + Arena* arena() { return spine_->arena(); } + + private: + RefCountedPtr spine_; +}; + +class UnstartedCallHandler { + public: + explicit UnstartedCallHandler(RefCountedPtr spine) + : spine_(std::move(spine)) {} + + void PushServerTrailingMetadata(ServerMetadataHandle status) { + spine_->PushServerTrailingMetadata(std::move(status)); } void OnDone(absl::AnyInvocable fn) { spine_->OnDone(std::move(fn)); } @@ -386,8 +467,9 @@ class CallHandler { } template - void SpawnGuarded(absl::string_view name, PromiseFactory promise_factory) { - spine_->SpawnGuarded(name, std::move(promise_factory)); + void SpawnGuarded(absl::string_view name, PromiseFactory promise_factory, + DebugLocation whence = {}) { + spine_->SpawnGuarded(name, std::move(promise_factory), whence); } template @@ -400,6 +482,11 @@ class CallHandler { return spine_->party().SpawnWaitable(name, std::move(promise_factory)); } + CallHandler V2HackToStartCallWithoutACallFilterStack() { + GPR_ASSERT(DownCast(spine_.get()) != nullptr); + return CallHandler(std::move(spine_)); + } + Arena* arena() { return spine_->arena(); } private: @@ -408,11 +495,13 @@ class CallHandler { struct CallInitiatorAndHandler { CallInitiator initiator; - CallHandler handler; + UnstartedCallHandler handler; }; CallInitiatorAndHandler MakeCall( - grpc_event_engine::experimental::EventEngine* event_engine, Arena* arena); + ClientMetadataHandle client_initial_metadata, + grpc_event_engine::experimental::EventEngine* event_engine, Arena* arena, + bool is_arena_owned); template auto OutgoingMessages(CallHalf h) { @@ -425,8 +514,7 @@ auto OutgoingMessages(CallHalf h) { // Forward a call from `call_handler` to `call_initiator` (with initial metadata // `client_initial_metadata`) -void ForwardCall(CallHandler call_handler, CallInitiator call_initiator, - ClientMetadataHandle client_initial_metadata); +void ForwardCall(CallHandler call_handler, CallInitiator call_initiator); } // namespace grpc_core diff --git a/src/core/lib/transport/transport.h b/src/core/lib/transport/transport.h index 9a89def3a8e..c824f0ae05c 100644 --- a/src/core/lib/transport/transport.h +++ b/src/core/lib/transport/transport.h @@ -559,7 +559,7 @@ class ServerTransport { // Create a call at the server (or fail) // arena must have been previously allocated by CreateArena() virtual absl::StatusOr CreateCall( - ClientMetadata& client_initial_metadata, Arena* arena) = 0; + ClientMetadataHandle client_initial_metadata, Arena* arena) = 0; protected: ~Acceptor() = default; diff --git a/src/core/load_balancing/grpclb/client_load_reporting_filter.cc b/src/core/load_balancing/grpclb/client_load_reporting_filter.cc index 3b139fa8a4c..c3de43e4b94 100644 --- a/src/core/load_balancing/grpclb/client_load_reporting_filter.cc +++ b/src/core/load_balancing/grpclb/client_load_reporting_filter.cc @@ -16,8 +16,6 @@ // // -#include - #include "src/core/load_balancing/grpclb/client_load_reporting_filter.h" #include @@ -27,7 +25,8 @@ #include "absl/types/optional.h" -#include "src/core/load_balancing/grpclb/grpclb_client_stats.h" +#include + #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/promise/context.h" @@ -36,48 +35,47 @@ #include "src/core/lib/resource_quota/arena.h" #include "src/core/lib/transport/metadata_batch.h" #include "src/core/lib/transport/transport.h" +#include "src/core/load_balancing/grpclb/grpclb_client_stats.h" namespace grpc_core { + +const NoInterceptor ClientLoadReportingFilter::Call::OnServerToClientMessage; +const NoInterceptor ClientLoadReportingFilter::Call::OnClientToServerMessage; +const NoInterceptor ClientLoadReportingFilter::Call::OnFinalize; + const grpc_channel_filter ClientLoadReportingFilter::kFilter = MakePromiseBasedFilter( "client_load_reporting"); -absl::StatusOr ClientLoadReportingFilter::Create( - const ChannelArgs&, ChannelFilter::Args) { - return ClientLoadReportingFilter(); +absl::StatusOr> +ClientLoadReportingFilter::Create(const ChannelArgs&, ChannelFilter::Args) { + return std::make_unique(); } -ArenaPromise ClientLoadReportingFilter::MakeCallPromise( - CallArgs call_args, NextPromiseFactory next_promise_factory) { - // Stats object to update. - RefCountedPtr client_stats; - +void ClientLoadReportingFilter::Call::OnClientInitialMetadata( + ClientMetadata& client_initial_metadata) { // Handle client initial metadata. // Grab client stats object from metadata. auto client_stats_md = - call_args.client_initial_metadata->Take(GrpcLbClientStatsMetadata()); + client_initial_metadata.Take(GrpcLbClientStatsMetadata()); if (client_stats_md.has_value()) { - client_stats.reset(*client_stats_md); + client_stats_.reset(*client_stats_md); } +} - auto* saw_initial_metadata = GetContext()->New(false); - call_args.server_initial_metadata->InterceptAndMap( - [saw_initial_metadata](ServerMetadataHandle md) { - *saw_initial_metadata = true; - return md; - }); +void ClientLoadReportingFilter::Call::OnServerInitialMetadata(ServerMetadata&) { + saw_initial_metadata_ = true; +} - return Map(next_promise_factory(std::move(call_args)), - [saw_initial_metadata, client_stats = std::move(client_stats)]( - ServerMetadataHandle trailing_metadata) { - if (client_stats != nullptr) { - client_stats->AddCallFinished( - trailing_metadata->get(GrpcStreamNetworkState()) == - GrpcStreamNetworkState::kNotSentOnWire, - *saw_initial_metadata); - } - return trailing_metadata; - }); +void ClientLoadReportingFilter::Call::OnServerTrailingMetadata( + ServerMetadata& server_trailing_metadata) { + if (client_stats_ != nullptr) { + client_stats_->AddCallFinished( + server_trailing_metadata.get(GrpcStreamNetworkState()) == + GrpcStreamNetworkState::kNotSentOnWire, + saw_initial_metadata_); + } } + } // namespace grpc_core diff --git a/src/core/load_balancing/grpclb/client_load_reporting_filter.h b/src/core/load_balancing/grpclb/client_load_reporting_filter.h index 57e89251d0b..941b97abf99 100644 --- a/src/core/load_balancing/grpclb/client_load_reporting_filter.h +++ b/src/core/load_balancing/grpclb/client_load_reporting_filter.h @@ -19,10 +19,10 @@ #ifndef GRPC_SRC_CORE_LOAD_BALANCING_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H #define GRPC_SRC_CORE_LOAD_BALANCING_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H -#include - #include "absl/status/statusor.h" +#include + #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_fwd.h" #include "src/core/lib/channel/promise_based_filter.h" @@ -31,16 +31,27 @@ namespace grpc_core { -class ClientLoadReportingFilter final : public ChannelFilter { +class ClientLoadReportingFilter final + : public ImplementChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + class Call { + public: + void OnClientInitialMetadata(ClientMetadata& client_initial_metadata); + void OnServerInitialMetadata(ServerMetadata& server_initial_metadata); + void OnServerTrailingMetadata(ServerMetadata& server_trailing_metadata); + static const NoInterceptor OnServerToClientMessage; + static const NoInterceptor OnClientToServerMessage; + static const NoInterceptor OnFinalize; + + private: + RefCountedPtr client_stats_; + bool saw_initial_metadata_ = false; + }; + + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args filter_args); - - // Construct a promise for one call. - ArenaPromise MakeCallPromise( - CallArgs call_args, NextPromiseFactory next_promise_factory) override; }; } // namespace grpc_core diff --git a/src/core/load_balancing/xds/xds_cluster_impl.cc b/src/core/load_balancing/xds/xds_cluster_impl.cc index ef766148021..acb1454a0b7 100644 --- a/src/core/load_balancing/xds/xds_cluster_impl.cc +++ b/src/core/load_balancing/xds/xds_cluster_impl.cc @@ -14,8 +14,6 @@ // limitations under the License. // -#include - #include #include @@ -36,6 +34,7 @@ #include #include +#include #include "src/core/client_channel/client_channel_internal.h" #include "src/core/ext/xds/xds_bootstrap.h" @@ -328,7 +327,9 @@ class XdsClusterImplLb::Picker::SubchannelCallTracker final ~SubchannelCallTracker() override { locality_stats_.reset(DEBUG_LOCATION, "SubchannelCallTracker"); call_counter_.reset(DEBUG_LOCATION, "SubchannelCallTracker"); +#ifndef NDEBUG GPR_DEBUG_ASSERT(!started_); +#endif } void Start() override { diff --git a/src/core/resolver/.clang-format b/src/core/resolver/.clang-format index 64387e9e515..5f150ef6edb 100644 --- a/src/core/resolver/.clang-format +++ b/src/core/resolver/.clang-format @@ -5,9 +5,6 @@ DerivePointerAlignment: false PointerAlignment: Left IncludeBlocks: Regroup IncludeCategories: - # port_platform.h is before almost everything - - Regex: '^' - Priority: -100 # ruby.h is even more first if it's included - Regex: '^' Priority: -200 diff --git a/src/core/resolver/xds/xds_resolver.cc b/src/core/resolver/xds/xds_resolver.cc index 6fc59c59113..13efe8a5099 100644 --- a/src/core/resolver/xds/xds_resolver.cc +++ b/src/core/resolver/xds/xds_resolver.cc @@ -317,9 +317,10 @@ class XdsResolver final : public Resolver { public: const static grpc_channel_filter kFilter; - static absl::StatusOr Create( - const ChannelArgs& /* unused */, ChannelFilter::Args filter_args) { - return ClusterSelectionFilter(filter_args); + static absl::StatusOr> Create( + const ChannelArgs& /* unused */, + ChannelFilter::Args /* filter_args */) { + return std::make_unique(); } // Construct a promise for one call. @@ -332,12 +333,6 @@ class XdsResolver final : public Resolver { static const NoInterceptor OnServerToClientMessage; static const NoInterceptor OnFinalize; }; - - private: - explicit ClusterSelectionFilter(ChannelFilter::Args filter_args) - : filter_args_(filter_args) {} - - ChannelFilter::Args filter_args_; }; RefCountedPtr GetOrCreateClusterRef( diff --git a/src/core/service_config/service_config_channel_arg_filter.cc b/src/core/service_config/service_config_channel_arg_filter.cc index 43069611022..a2c9a973129 100644 --- a/src/core/service_config/service_config_channel_arg_filter.cc +++ b/src/core/service_config/service_config_channel_arg_filter.cc @@ -17,8 +17,6 @@ // This filter reads GRPC_ARG_SERVICE_CONFIG and populates ServiceConfigCallData // in the call context per call for direct channels. -#include - #include #include #include @@ -30,6 +28,7 @@ #include #include +#include #include "src/core/ext/filters/message_size/message_size_filter.h" #include "src/core/lib/channel/channel_args.h" @@ -42,13 +41,13 @@ #include "src/core/lib/promise/arena_promise.h" #include "src/core/lib/promise/context.h" #include "src/core/lib/resource_quota/arena.h" +#include "src/core/lib/surface/channel_stack_type.h" +#include "src/core/lib/transport/metadata_batch.h" +#include "src/core/lib/transport/transport.h" #include "src/core/service_config/service_config.h" #include "src/core/service_config/service_config_call_data.h" #include "src/core/service_config/service_config_impl.h" #include "src/core/service_config/service_config_parser.h" -#include "src/core/lib/surface/channel_stack_type.h" -#include "src/core/lib/transport/metadata_batch.h" -#include "src/core/lib/transport/transport.h" namespace grpc_core { @@ -59,9 +58,9 @@ class ServiceConfigChannelArgFilter final public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs& args, ChannelFilter::Args) { - return ServiceConfigChannelArgFilter(args); + return std::make_unique(args); } explicit ServiceConfigChannelArgFilter(const ChannelArgs& args) { diff --git a/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc b/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc index 98cf9bbec93..ac7372cb464 100644 --- a/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc +++ b/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc @@ -24,6 +24,7 @@ #include "upb/mem/arena.hpp" +#include #include #include #include diff --git a/src/core/tsi/ssl_transport_security.cc b/src/core/tsi/ssl_transport_security.cc index 9235782bb29..d705abc1c2c 100644 --- a/src/core/tsi/ssl_transport_security.cc +++ b/src/core/tsi/ssl_transport_security.cc @@ -1282,6 +1282,10 @@ void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache) { tsi::SslSessionLRUCache::FromC(cache)->Unref(); } +size_t tsi_ssl_session_cache_size(tsi_ssl_session_cache* cache) { + return tsi::SslSessionLRUCache::FromC(cache)->Size(); +} + // --- tsi_frame_protector methods implementation. --- static tsi_result ssl_protector_protect(tsi_frame_protector* self, diff --git a/src/core/tsi/ssl_transport_security.h b/src/core/tsi/ssl_transport_security.h index da3b260adbd..d925f08840b 100644 --- a/src/core/tsi/ssl_transport_security.h +++ b/src/core/tsi/ssl_transport_security.h @@ -81,6 +81,9 @@ void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache); // Decrement reference counter of \a cache. void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache); +// Returns the size of the cache. +size_t tsi_ssl_session_cache_size(tsi_ssl_session_cache* cache); + // --- tsi_ssl_key_logger object --- // Experimental SSL Key logging functionality to enable decryption of diff --git a/src/cpp/client/create_channel_posix.cc b/src/cpp/client/create_channel_posix.cc index d260f1c68c7..e1d6653ed55 100644 --- a/src/cpp/client/create_channel_posix.cc +++ b/src/cpp/client/create_channel_posix.cc @@ -21,6 +21,7 @@ #include #include +#include #include #include #include diff --git a/src/cpp/common/tls_certificate_provider.cc b/src/cpp/common/tls_certificate_provider.cc index c51c0ea5892..e978a085bee 100644 --- a/src/cpp/common/tls_certificate_provider.cc +++ b/src/cpp/common/tls_certificate_provider.cc @@ -17,6 +17,7 @@ #include #include +#include #include #include #include diff --git a/src/cpp/common/tls_certificate_verifier.cc b/src/cpp/common/tls_certificate_verifier.cc index 093062a6202..9e717d0714a 100644 --- a/src/cpp/common/tls_certificate_verifier.cc +++ b/src/cpp/common/tls_certificate_verifier.cc @@ -22,6 +22,7 @@ #include #include +#include #include #include #include diff --git a/src/cpp/common/tls_credentials_options.cc b/src/cpp/common/tls_credentials_options.cc index 56664e501fd..77af87b1280 100644 --- a/src/cpp/common/tls_credentials_options.cc +++ b/src/cpp/common/tls_credentials_options.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include diff --git a/src/cpp/ext/filters/census/client_filter.cc b/src/cpp/ext/filters/census/client_filter.cc index 8dbc0959bd7..16131ce8af4 100644 --- a/src/cpp/ext/filters/census/client_filter.cc +++ b/src/cpp/ext/filters/census/client_filter.cc @@ -84,11 +84,13 @@ const grpc_channel_filter OpenCensusClientFilter::kFilter = grpc_core::FilterEndpoint::kClient, 0>( "opencensus_client"); -absl::StatusOr OpenCensusClientFilter::Create( - const grpc_core::ChannelArgs& args, ChannelFilter::Args /*filter_args*/) { +absl::StatusOr> +OpenCensusClientFilter::Create(const grpc_core::ChannelArgs& args, + ChannelFilter::Args /*filter_args*/) { bool observability_enabled = args.GetInt(GRPC_ARG_ENABLE_OBSERVABILITY).value_or(true); - return OpenCensusClientFilter(/*tracing_enabled=*/observability_enabled); + return std::make_unique( + /*tracing_enabled=*/observability_enabled); } grpc_core::ArenaPromise diff --git a/src/cpp/ext/filters/census/client_filter.h b/src/cpp/ext/filters/census/client_filter.h index 011a22e58a1..a549510bbe2 100644 --- a/src/cpp/ext/filters/census/client_filter.h +++ b/src/cpp/ext/filters/census/client_filter.h @@ -38,16 +38,17 @@ class OpenCensusClientFilter : public grpc_core::ChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + static absl::StatusOr> Create( const grpc_core::ChannelArgs& args, ChannelFilter::Args /*filter_args*/); + explicit OpenCensusClientFilter(bool tracing_enabled) + : tracing_enabled_(tracing_enabled) {} + grpc_core::ArenaPromise MakeCallPromise( grpc_core::CallArgs call_args, grpc_core::NextPromiseFactory next_promise_factory) override; private: - explicit OpenCensusClientFilter(bool tracing_enabled) - : tracing_enabled_(tracing_enabled) {} bool tracing_enabled_ = true; }; diff --git a/src/cpp/ext/otel/BUILD b/src/cpp/ext/otel/BUILD index 588c769652d..8a1ca1affa6 100644 --- a/src/cpp/ext/otel/BUILD +++ b/src/cpp/ext/otel/BUILD @@ -57,7 +57,7 @@ grpc_cc_library( "otel/api", ], language = "c++", - visibility = ["//:__subpackages__"], + visibility = ["@grpc:otel_plugin"], deps = [ "//:call_tracer", "//:config", diff --git a/src/cpp/server/server_builder.cc b/src/cpp/server/server_builder.cc index 6d5924404f4..d79f3df4d1f 100644 --- a/src/cpp/server/server_builder.cc +++ b/src/cpp/server/server_builder.cc @@ -15,7 +15,6 @@ // limitations under the License. // // - #include #include @@ -29,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -45,11 +45,38 @@ #include #include +#include "src/core/ext/transport/chttp2/server/chttp2_server.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/useful.h" +#include "src/core/lib/surface/server.h" #include "src/cpp/server/external_connection_acceptor_impl.h" namespace grpc { +namespace { + +// A PIMPL wrapper class that owns the only ref to the passive listener +// implementation. This is returned to the application. +class PassiveListenerOwner final + : public grpc_core::experimental::PassiveListener { + public: + explicit PassiveListenerOwner(std::shared_ptr listener) + : listener_(std::move(listener)) {} + + absl::Status AcceptConnectedEndpoint( + std::unique_ptr + endpoint) override { + return listener_->AcceptConnectedEndpoint(std::move(endpoint)); + } + + absl::Status AcceptConnectedFd(int fd) override { + return listener_->AcceptConnectedFd(fd); + } + + private: + std::shared_ptr listener_; +}; + +} // namespace static std::vector (*)()>* g_plugin_factory_list; @@ -223,6 +250,18 @@ ServerBuilder& ServerBuilder::SetResourceQuota( return *this; } +ServerBuilder& ServerBuilder::experimental_type::AddPassiveListener( + std::shared_ptr creds, + std::unique_ptr& passive_listener) { + auto core_passive_listener = + std::make_shared(); + builder_->unstarted_passive_listeners_.emplace_back(core_passive_listener, + std::move(creds)); + passive_listener = + std::make_unique(std::move(core_passive_listener)); + return *builder_; +} + ServerBuilder& ServerBuilder::AddListeningPort( const std::string& addr_uri, std::shared_ptr creds, int* selected_port) { @@ -396,6 +435,26 @@ std::unique_ptr ServerBuilder::BuildAndStart() { cq->RegisterServer(server.get()); } + for (auto& unstarted_listener : unstarted_passive_listeners_) { + has_frequently_polled_cqs = true; + auto passive_listener = unstarted_listener.passive_listener.lock(); + auto* core_server = grpc_core::Server::FromC(server->c_server()); + if (passive_listener != nullptr) { + auto* creds = unstarted_listener.credentials->c_creds(); + if (creds == nullptr) { + gpr_log(GPR_ERROR, "Credentials missing for PassiveListener"); + return nullptr; + } + auto success = grpc_server_add_passive_listener( + core_server, creds, std::move(passive_listener)); + if (!success.ok()) { + gpr_log(GPR_ERROR, "Failed to create a passive listener: %s", + success.ToString().c_str()); + return nullptr; + } + } + } + if (!has_frequently_polled_cqs) { gpr_log(GPR_ERROR, "At least one of the completion queues must be frequently polled"); diff --git a/src/cpp/server/server_posix.cc b/src/cpp/server/server_posix.cc index ecc1848a1fc..3491ca58c3c 100644 --- a/src/cpp/server/server_posix.cc +++ b/src/cpp/server/server_posix.cc @@ -16,6 +16,7 @@ // // +#include #include #include #include diff --git a/src/objective-c/GRPCClient/private/GRPCCore/GRPCInsecureChannelFactory.mm b/src/objective-c/GRPCClient/private/GRPCCore/GRPCInsecureChannelFactory.mm index 89679ba2989..28039fd2390 100644 --- a/src/objective-c/GRPCClient/private/GRPCCore/GRPCInsecureChannelFactory.mm +++ b/src/objective-c/GRPCClient/private/GRPCCore/GRPCInsecureChannelFactory.mm @@ -18,6 +18,7 @@ #import "GRPCInsecureChannelFactory.h" +#include #include #import "ChannelArgsUtil.h" diff --git a/src/objective-c/GRPCClient/private/GRPCCore/GRPCSecureChannelFactory.mm b/src/objective-c/GRPCClient/private/GRPCCore/GRPCSecureChannelFactory.mm index 8321ac5b35f..1c884b461cc 100644 --- a/src/objective-c/GRPCClient/private/GRPCCore/GRPCSecureChannelFactory.mm +++ b/src/objective-c/GRPCClient/private/GRPCCore/GRPCSecureChannelFactory.mm @@ -19,6 +19,7 @@ #import "GRPCSecureChannelFactory.h" #import +#include #include #import "ChannelArgsUtil.h" diff --git a/src/php/ext/grpc/call_credentials.h b/src/php/ext/grpc/call_credentials.h index e0cc8638534..e82520802b0 100644 --- a/src/php/ext/grpc/call_credentials.h +++ b/src/php/ext/grpc/call_credentials.h @@ -21,6 +21,7 @@ #include "php_grpc.h" +#include #include /* Class entry for the CallCredentials PHP class */ diff --git a/src/php/ext/grpc/channel.c b/src/php/ext/grpc/channel.c index 8cac73ffd7d..0dca12debfa 100644 --- a/src/php/ext/grpc/channel.c +++ b/src/php/ext/grpc/channel.c @@ -29,6 +29,7 @@ #include #include +#include #include #include #include diff --git a/src/php/ext/grpc/channel_credentials.h b/src/php/ext/grpc/channel_credentials.h index 7c6cf30367d..c790f3e6524 100644 --- a/src/php/ext/grpc/channel_credentials.h +++ b/src/php/ext/grpc/channel_credentials.h @@ -21,6 +21,7 @@ #include "php_grpc.h" +#include #include /* Class entry for the ChannelCredentials PHP class */ diff --git a/src/php/ext/grpc/php_grpc.c b/src/php/ext/grpc/php_grpc.c index 8a0aa075fdf..7541729f15a 100644 --- a/src/php/ext/grpc/php_grpc.c +++ b/src/php/ext/grpc/php_grpc.c @@ -28,6 +28,7 @@ #include "server_credentials.h" #include "completion_queue.h" #include +#include #include #include #include diff --git a/src/php/ext/grpc/server.c b/src/php/ext/grpc/server.c index 2001760e349..ebedb184c72 100644 --- a/src/php/ext/grpc/server.c +++ b/src/php/ext/grpc/server.c @@ -26,6 +26,7 @@ #include #include +#include #include #include #include diff --git a/src/php/ext/grpc/server_credentials.h b/src/php/ext/grpc/server_credentials.h index 6a1af3603ed..91edf262481 100644 --- a/src/php/ext/grpc/server_credentials.h +++ b/src/php/ext/grpc/server_credentials.h @@ -21,6 +21,7 @@ #include "php_grpc.h" +#include #include /* Class entry for the Server_Credentials PHP class */ diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi index 29149e9893a..ce9a1d85e6b 100644 --- a/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi +++ b/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi @@ -445,6 +445,9 @@ cdef extern from "grpc/grpc.h": grpc_channel *channel, grpc_connectivity_state last_observed_state, gpr_timespec deadline, grpc_completion_queue *cq, void *tag) nogil char *grpc_channel_get_target(grpc_channel *channel) nogil + grpc_channel *grpc_channel_create( + const char *target, grpc_channel_credentials *creds, + const grpc_channel_args *args) nogil void grpc_channel_destroy(grpc_channel *channel) nogil grpc_server *grpc_server_create( @@ -493,17 +496,18 @@ cdef extern from "grpc/grpc.h": grpc_slice grpc_dump_xds_configs() nogil + ctypedef struct grpc_server_credentials: + # We don't care about the internals (and in fact don't know them) + pass -cdef extern from "grpc/grpc_security.h": - - # Declare this as an enum, this is the only way to make it a const in - # cython - enum: GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX +cdef extern from "grpc/grpc_security_constants.h": - ctypedef enum grpc_ssl_roots_override_result: - GRPC_SSL_ROOTS_OVERRIDE_OK - GRPC_SSL_ROOTS_OVERRIDE_FAILED_PERMANENTLY - GRPC_SSL_ROOTS_OVERRIDE_FAILED + ctypedef enum grpc_security_level: + GRPC_SECURITY_MIN + GRPC_SECURITY_NONE = GRPC_SECURITY_MIN + GRPC_INTEGRITY_ONLY + GRPC_PRIVACY_AND_INTEGRITY + GRPC_SECURITY_MAX = GRPC_PRIVACY_AND_INTEGRITY ctypedef enum grpc_ssl_client_certificate_request_type: GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE, @@ -512,18 +516,31 @@ cdef extern from "grpc/grpc_security.h": GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY - ctypedef enum grpc_security_level: - GRPC_SECURITY_MIN - GRPC_SECURITY_NONE = GRPC_SECURITY_MIN - GRPC_INTEGRITY_ONLY - GRPC_PRIVACY_AND_INTEGRITY - GRPC_SECURITY_MAX = GRPC_PRIVACY_AND_INTEGRITY + ctypedef enum grpc_ssl_roots_override_result: + GRPC_SSL_ROOTS_OVERRIDE_OK + GRPC_SSL_ROOTS_OVERRIDE_FAILED_PERMANENTLY + GRPC_SSL_ROOTS_OVERRIDE_FAILED ctypedef enum grpc_ssl_certificate_config_reload_status: GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL + ctypedef grpc_ssl_certificate_config_reload_status (*grpc_ssl_server_certificate_config_callback)( + void *user_data, + grpc_ssl_server_certificate_config **config) + + ctypedef struct grpc_auth_property_iterator: + pass + + ctypedef struct grpc_auth_property: + char *name + char *value + size_t value_length + + +cdef extern from "grpc/credentials.h": + ctypedef struct grpc_ssl_server_certificate_config: # We don't care about the internals pass @@ -539,10 +556,6 @@ cdef extern from "grpc/grpc_security.h": void grpc_ssl_server_certificate_config_destroy(grpc_ssl_server_certificate_config *config) - ctypedef grpc_ssl_certificate_config_reload_status (*grpc_ssl_server_certificate_config_callback)( - void *user_data, - grpc_ssl_server_certificate_config **config) - grpc_ssl_server_credentials_options *grpc_ssl_server_credentials_create_options_using_config( grpc_ssl_client_certificate_request_type client_certificate_request, grpc_ssl_server_certificate_config *certificate_config) @@ -567,23 +580,12 @@ cdef extern from "grpc/grpc_security.h": # We don't care about the internals (and in fact don't know them) pass - ctypedef struct grpc_ssl_session_cache: - # We don't care about the internals (and in fact don't know them) - pass - ctypedef struct verify_peer_options: # We don't care about the internals (and in fact don't know them) pass - ctypedef void (*grpc_ssl_roots_override_callback)(char **pem_root_certs) - - grpc_ssl_session_cache *grpc_ssl_session_cache_create_lru(size_t capacity) - void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache) - - void grpc_set_ssl_roots_override_callback( - grpc_ssl_roots_override_callback cb) nogil - grpc_channel_credentials *grpc_google_default_credentials_create(grpc_call_credentials* call_credentials) nogil + grpc_channel_credentials *grpc_ssl_credentials_create( const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pair, verify_peer_options *verify_options, void *reserved) nogil @@ -605,33 +607,22 @@ cdef extern from "grpc/grpc_security.h": grpc_call_credentials *grpc_composite_call_credentials_create( grpc_call_credentials *creds1, grpc_call_credentials *creds2, void *reserved) nogil + grpc_call_credentials *grpc_google_compute_engine_credentials_create( void *reserved) nogil + grpc_call_credentials *grpc_service_account_jwt_access_credentials_create( const char *json_key, gpr_timespec token_lifetime, void *reserved) nogil + grpc_call_credentials *grpc_google_refresh_token_credentials_create( const char *json_refresh_token, void *reserved) nogil + grpc_call_credentials *grpc_google_iam_credentials_create( const char *authorization_token, const char *authority_selector, void *reserved) nogil - void grpc_call_credentials_release(grpc_call_credentials *creds) nogil - - grpc_channel *grpc_channel_create( - const char *target, grpc_channel_credentials *creds, - const grpc_channel_args *args) nogil - - ctypedef struct grpc_server_credentials: - # We don't care about the internals (and in fact don't know them) - pass - void grpc_server_credentials_release(grpc_server_credentials *creds) nogil - - int grpc_server_add_http2_port(grpc_server *server, const char *addr, - grpc_server_credentials *creds) nogil - - grpc_call_error grpc_call_set_credentials(grpc_call *call, - grpc_call_credentials *creds) nogil + void grpc_call_credentials_release(grpc_call_credentials *creds) nogil ctypedef struct grpc_auth_context: # We don't care about the internals (and in fact don't know them) @@ -646,6 +637,10 @@ cdef extern from "grpc/grpc_security.h": void *user_data, const grpc_metadata *creds_md, size_t num_creds_md, grpc_status_code status, const char *error_details) nogil + # Declare this as an enum, this is the only way to make it a const in + # cython + enum: GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX + ctypedef struct grpc_metadata_credentials_plugin: int (*get_metadata)( void *state, grpc_auth_metadata_context context, @@ -660,13 +655,47 @@ cdef extern from "grpc/grpc_security.h": grpc_call_credentials *grpc_metadata_credentials_create_from_plugin( grpc_metadata_credentials_plugin plugin, grpc_security_level min_security_level, void *reserved) nogil - ctypedef struct grpc_auth_property_iterator: + grpc_channel_credentials *grpc_local_credentials_create( + grpc_local_connect_type type) + grpc_server_credentials *grpc_local_server_credentials_create( + grpc_local_connect_type type) + + ctypedef struct grpc_alts_credentials_options: + # We don't care about the internals (and in fact don't know them) pass - ctypedef struct grpc_auth_property: - char *name - char *value - size_t value_length + grpc_channel_credentials *grpc_alts_credentials_create( + const grpc_alts_credentials_options *options) + grpc_server_credentials *grpc_alts_server_credentials_create( + const grpc_alts_credentials_options *options) + + grpc_alts_credentials_options* grpc_alts_credentials_client_options_create() + grpc_alts_credentials_options* grpc_alts_credentials_server_options_create() + void grpc_alts_credentials_options_destroy(grpc_alts_credentials_options *options) + void grpc_alts_credentials_client_options_add_target_service_account(grpc_alts_credentials_options *options, const char *service_account) + + +cdef extern from "grpc/grpc_security.h": + + ctypedef struct grpc_ssl_session_cache: + # We don't care about the internals (and in fact don't know them) + pass + + ctypedef void (*grpc_ssl_roots_override_callback)(char **pem_root_certs) + + grpc_ssl_session_cache *grpc_ssl_session_cache_create_lru(size_t capacity) + void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache) + + void grpc_set_ssl_roots_override_callback( + grpc_ssl_roots_override_callback cb) nogil + + void grpc_server_credentials_release(grpc_server_credentials *creds) nogil + + int grpc_server_add_http2_port(grpc_server *server, const char *addr, + grpc_server_credentials *creds) nogil + + grpc_call_error grpc_call_set_credentials(grpc_call *call, + grpc_call_credentials *creds) nogil grpc_auth_property *grpc_auth_property_iterator_next( grpc_auth_property_iterator *it) @@ -690,26 +719,6 @@ cdef extern from "grpc/grpc_security.h": void grpc_auth_context_release(grpc_auth_context *context) - grpc_channel_credentials *grpc_local_credentials_create( - grpc_local_connect_type type) - grpc_server_credentials *grpc_local_server_credentials_create( - grpc_local_connect_type type) - - ctypedef struct grpc_alts_credentials_options: - # We don't care about the internals (and in fact don't know them) - pass - - grpc_channel_credentials *grpc_alts_credentials_create( - const grpc_alts_credentials_options *options) - grpc_server_credentials *grpc_alts_server_credentials_create( - const grpc_alts_credentials_options *options) - - grpc_alts_credentials_options* grpc_alts_credentials_client_options_create() - grpc_alts_credentials_options* grpc_alts_credentials_server_options_create() - void grpc_alts_credentials_options_destroy(grpc_alts_credentials_options *options) - void grpc_alts_credentials_client_options_add_target_service_account(grpc_alts_credentials_options *options, const char *service_account) - - cdef extern from "grpc/compression.h": diff --git a/src/ruby/ext/grpc/rb_call_credentials.c b/src/ruby/ext/grpc/rb_call_credentials.c index 4d4420cbac4..1afcfbdcc74 100644 --- a/src/ruby/ext/grpc/rb_call_credentials.c +++ b/src/ruby/ext/grpc/rb_call_credentials.c @@ -27,6 +27,7 @@ #include "rb_grpc.h" #include "rb_grpc_imports.generated.h" +#include #include #include #include diff --git a/src/ruby/ext/grpc/rb_call_credentials.h b/src/ruby/ext/grpc/rb_call_credentials.h index 35c48f83371..785a773aff3 100644 --- a/src/ruby/ext/grpc/rb_call_credentials.h +++ b/src/ruby/ext/grpc/rb_call_credentials.h @@ -21,6 +21,7 @@ #include +#include #include /* Initializes the ruby CallCredentials class. */ diff --git a/src/ruby/ext/grpc/rb_channel.c b/src/ruby/ext/grpc/rb_channel.c index 165708e6951..48099c258b6 100644 --- a/src/ruby/ext/grpc/rb_channel.c +++ b/src/ruby/ext/grpc/rb_channel.c @@ -32,6 +32,7 @@ #include "rb_server.h" #include "rb_xds_channel_credentials.h" +#include #include #include #include diff --git a/src/ruby/ext/grpc/rb_channel_credentials.c b/src/ruby/ext/grpc/rb_channel_credentials.c index 8382fb1f904..e570bfb707f 100644 --- a/src/ruby/ext/grpc/rb_channel_credentials.c +++ b/src/ruby/ext/grpc/rb_channel_credentials.c @@ -26,6 +26,7 @@ #include "rb_grpc.h" #include "rb_grpc_imports.generated.h" +#include #include #include #include diff --git a/src/ruby/ext/grpc/rb_grpc_imports.generated.c b/src/ruby/ext/grpc/rb_grpc_imports.generated.c index 302dbf49f44..e4607ce6d00 100644 --- a/src/ruby/ext/grpc/rb_grpc_imports.generated.c +++ b/src/ruby/ext/grpc/rb_grpc_imports.generated.c @@ -42,6 +42,70 @@ grpc_compression_options_init_type grpc_compression_options_init_import; grpc_compression_options_enable_algorithm_type grpc_compression_options_enable_algorithm_import; grpc_compression_options_disable_algorithm_type grpc_compression_options_disable_algorithm_import; grpc_compression_options_is_algorithm_enabled_type grpc_compression_options_is_algorithm_enabled_import; +grpc_service_account_jwt_access_credentials_create_type grpc_service_account_jwt_access_credentials_create_import; +grpc_external_account_credentials_create_type grpc_external_account_credentials_create_import; +grpc_google_refresh_token_credentials_create_type grpc_google_refresh_token_credentials_create_import; +grpc_access_token_credentials_create_type grpc_access_token_credentials_create_import; +grpc_google_iam_credentials_create_type grpc_google_iam_credentials_create_import; +grpc_sts_credentials_create_type grpc_sts_credentials_create_import; +grpc_auth_metadata_context_copy_type grpc_auth_metadata_context_copy_import; +grpc_auth_metadata_context_reset_type grpc_auth_metadata_context_reset_import; +grpc_metadata_credentials_create_from_plugin_type grpc_metadata_credentials_create_from_plugin_import; +grpc_call_credentials_release_type grpc_call_credentials_release_import; +grpc_google_default_credentials_create_type grpc_google_default_credentials_create_import; +grpc_ssl_server_certificate_config_create_type grpc_ssl_server_certificate_config_create_import; +grpc_ssl_server_certificate_config_destroy_type grpc_ssl_server_certificate_config_destroy_import; +grpc_ssl_credentials_create_type grpc_ssl_credentials_create_import; +grpc_ssl_credentials_create_ex_type grpc_ssl_credentials_create_ex_import; +grpc_ssl_server_credentials_create_type grpc_ssl_server_credentials_create_import; +grpc_ssl_server_credentials_create_ex_type grpc_ssl_server_credentials_create_ex_import; +grpc_ssl_server_credentials_create_options_using_config_type grpc_ssl_server_credentials_create_options_using_config_import; +grpc_ssl_server_credentials_create_options_using_config_fetcher_type grpc_ssl_server_credentials_create_options_using_config_fetcher_import; +grpc_ssl_server_credentials_options_destroy_type grpc_ssl_server_credentials_options_destroy_import; +grpc_ssl_server_credentials_create_with_options_type grpc_ssl_server_credentials_create_with_options_import; +grpc_server_credentials_set_auth_metadata_processor_type grpc_server_credentials_set_auth_metadata_processor_import; +grpc_composite_call_credentials_create_type grpc_composite_call_credentials_create_import; +grpc_google_compute_engine_credentials_create_type grpc_google_compute_engine_credentials_create_import; +grpc_composite_channel_credentials_create_type grpc_composite_channel_credentials_create_import; +grpc_alts_credentials_client_options_create_type grpc_alts_credentials_client_options_create_import; +grpc_alts_credentials_server_options_create_type grpc_alts_credentials_server_options_create_import; +grpc_alts_credentials_client_options_add_target_service_account_type grpc_alts_credentials_client_options_add_target_service_account_import; +grpc_alts_credentials_options_destroy_type grpc_alts_credentials_options_destroy_import; +grpc_alts_credentials_create_type grpc_alts_credentials_create_import; +grpc_alts_server_credentials_create_type grpc_alts_server_credentials_create_import; +grpc_tls_identity_pairs_create_type grpc_tls_identity_pairs_create_import; +grpc_tls_identity_pairs_add_pair_type grpc_tls_identity_pairs_add_pair_import; +grpc_tls_identity_pairs_destroy_type grpc_tls_identity_pairs_destroy_import; +grpc_tls_certificate_provider_static_data_create_type grpc_tls_certificate_provider_static_data_create_import; +grpc_tls_certificate_provider_file_watcher_create_type grpc_tls_certificate_provider_file_watcher_create_import; +grpc_tls_certificate_provider_release_type grpc_tls_certificate_provider_release_import; +grpc_tls_credentials_options_create_type grpc_tls_credentials_options_create_import; +grpc_tls_credentials_options_set_min_tls_version_type grpc_tls_credentials_options_set_min_tls_version_import; +grpc_tls_credentials_options_set_max_tls_version_type grpc_tls_credentials_options_set_max_tls_version_import; +grpc_tls_credentials_options_copy_type grpc_tls_credentials_options_copy_import; +grpc_tls_credentials_options_destroy_type grpc_tls_credentials_options_destroy_import; +grpc_tls_credentials_options_set_certificate_provider_type grpc_tls_credentials_options_set_certificate_provider_import; +grpc_tls_credentials_options_watch_root_certs_type grpc_tls_credentials_options_watch_root_certs_import; +grpc_tls_credentials_options_set_root_cert_name_type grpc_tls_credentials_options_set_root_cert_name_import; +grpc_tls_credentials_options_watch_identity_key_cert_pairs_type grpc_tls_credentials_options_watch_identity_key_cert_pairs_import; +grpc_tls_credentials_options_set_identity_cert_name_type grpc_tls_credentials_options_set_identity_cert_name_import; +grpc_tls_credentials_options_set_cert_request_type_type grpc_tls_credentials_options_set_cert_request_type_import; +grpc_tls_credentials_options_set_crl_directory_type grpc_tls_credentials_options_set_crl_directory_import; +grpc_tls_credentials_options_set_verify_server_cert_type grpc_tls_credentials_options_set_verify_server_cert_import; +grpc_tls_credentials_options_set_send_client_ca_list_type grpc_tls_credentials_options_set_send_client_ca_list_import; +grpc_ssl_session_cache_create_lru_type grpc_ssl_session_cache_create_lru_import; +grpc_ssl_session_cache_destroy_type grpc_ssl_session_cache_destroy_import; +grpc_ssl_session_cache_create_channel_arg_type grpc_ssl_session_cache_create_channel_arg_import; +grpc_set_ssl_roots_override_callback_type grpc_set_ssl_roots_override_callback_import; +grpc_max_auth_token_lifetime_type grpc_max_auth_token_lifetime_import; +grpc_insecure_credentials_create_type grpc_insecure_credentials_create_import; +grpc_insecure_server_credentials_create_type grpc_insecure_server_credentials_create_import; +grpc_xds_credentials_create_type grpc_xds_credentials_create_import; +grpc_xds_server_credentials_create_type grpc_xds_server_credentials_create_import; +grpc_local_credentials_create_type grpc_local_credentials_create_import; +grpc_local_server_credentials_create_type grpc_local_server_credentials_create_import; +grpc_tls_credentials_options_set_check_call_host_type grpc_tls_credentials_options_set_check_call_host_import; +grpc_tls_credentials_options_set_tls_session_key_log_file_path_type grpc_tls_credentials_options_set_tls_session_key_log_file_path_import; grpc_metadata_array_init_type grpc_metadata_array_init_import; grpc_metadata_array_destroy_type grpc_metadata_array_destroy_import; grpc_call_details_init_type grpc_call_details_init_import; @@ -87,6 +151,7 @@ grpc_call_cancel_with_status_type grpc_call_cancel_with_status_import; grpc_call_failed_before_recv_message_type grpc_call_failed_before_recv_message_import; grpc_call_ref_type grpc_call_ref_import; grpc_call_unref_type grpc_call_unref_import; +grpc_call_set_credentials_type grpc_call_set_credentials_import; grpc_server_request_call_type grpc_server_request_call_import; grpc_server_register_method_type grpc_server_register_method_import; grpc_server_request_registered_call_type grpc_server_request_registered_call_import; @@ -133,74 +198,9 @@ grpc_auth_context_release_type grpc_auth_context_release_import; grpc_auth_context_add_property_type grpc_auth_context_add_property_import; grpc_auth_context_add_cstring_property_type grpc_auth_context_add_cstring_property_import; grpc_auth_context_set_peer_identity_property_name_type grpc_auth_context_set_peer_identity_property_name_import; -grpc_ssl_session_cache_create_lru_type grpc_ssl_session_cache_create_lru_import; -grpc_ssl_session_cache_destroy_type grpc_ssl_session_cache_destroy_import; -grpc_ssl_session_cache_create_channel_arg_type grpc_ssl_session_cache_create_channel_arg_import; -grpc_call_credentials_release_type grpc_call_credentials_release_import; -grpc_google_default_credentials_create_type grpc_google_default_credentials_create_import; -grpc_set_ssl_roots_override_callback_type grpc_set_ssl_roots_override_callback_import; -grpc_ssl_credentials_create_type grpc_ssl_credentials_create_import; -grpc_ssl_credentials_create_ex_type grpc_ssl_credentials_create_ex_import; -grpc_composite_channel_credentials_create_type grpc_composite_channel_credentials_create_import; -grpc_composite_call_credentials_create_type grpc_composite_call_credentials_create_import; -grpc_google_compute_engine_credentials_create_type grpc_google_compute_engine_credentials_create_import; -grpc_max_auth_token_lifetime_type grpc_max_auth_token_lifetime_import; -grpc_service_account_jwt_access_credentials_create_type grpc_service_account_jwt_access_credentials_create_import; -grpc_external_account_credentials_create_type grpc_external_account_credentials_create_import; -grpc_google_refresh_token_credentials_create_type grpc_google_refresh_token_credentials_create_import; -grpc_access_token_credentials_create_type grpc_access_token_credentials_create_import; -grpc_google_iam_credentials_create_type grpc_google_iam_credentials_create_import; -grpc_sts_credentials_create_type grpc_sts_credentials_create_import; -grpc_auth_metadata_context_copy_type grpc_auth_metadata_context_copy_import; -grpc_auth_metadata_context_reset_type grpc_auth_metadata_context_reset_import; -grpc_metadata_credentials_create_from_plugin_type grpc_metadata_credentials_create_from_plugin_import; -grpc_ssl_server_certificate_config_create_type grpc_ssl_server_certificate_config_create_import; -grpc_ssl_server_certificate_config_destroy_type grpc_ssl_server_certificate_config_destroy_import; -grpc_ssl_server_credentials_create_type grpc_ssl_server_credentials_create_import; -grpc_ssl_server_credentials_create_ex_type grpc_ssl_server_credentials_create_ex_import; -grpc_ssl_server_credentials_create_options_using_config_type grpc_ssl_server_credentials_create_options_using_config_import; -grpc_ssl_server_credentials_create_options_using_config_fetcher_type grpc_ssl_server_credentials_create_options_using_config_fetcher_import; -grpc_ssl_server_credentials_options_destroy_type grpc_ssl_server_credentials_options_destroy_import; -grpc_ssl_server_credentials_create_with_options_type grpc_ssl_server_credentials_create_with_options_import; -grpc_call_set_credentials_type grpc_call_set_credentials_import; -grpc_server_credentials_set_auth_metadata_processor_type grpc_server_credentials_set_auth_metadata_processor_import; -grpc_alts_credentials_client_options_create_type grpc_alts_credentials_client_options_create_import; -grpc_alts_credentials_server_options_create_type grpc_alts_credentials_server_options_create_import; -grpc_alts_credentials_client_options_add_target_service_account_type grpc_alts_credentials_client_options_add_target_service_account_import; -grpc_alts_credentials_options_destroy_type grpc_alts_credentials_options_destroy_import; -grpc_alts_credentials_create_type grpc_alts_credentials_create_import; -grpc_alts_server_credentials_create_type grpc_alts_server_credentials_create_import; -grpc_local_credentials_create_type grpc_local_credentials_create_import; -grpc_local_server_credentials_create_type grpc_local_server_credentials_create_import; -grpc_tls_identity_pairs_create_type grpc_tls_identity_pairs_create_import; -grpc_tls_identity_pairs_add_pair_type grpc_tls_identity_pairs_add_pair_import; -grpc_tls_identity_pairs_destroy_type grpc_tls_identity_pairs_destroy_import; -grpc_tls_certificate_provider_static_data_create_type grpc_tls_certificate_provider_static_data_create_import; -grpc_tls_certificate_provider_file_watcher_create_type grpc_tls_certificate_provider_file_watcher_create_import; -grpc_tls_certificate_provider_release_type grpc_tls_certificate_provider_release_import; -grpc_tls_credentials_options_create_type grpc_tls_credentials_options_create_import; -grpc_tls_credentials_options_set_min_tls_version_type grpc_tls_credentials_options_set_min_tls_version_import; -grpc_tls_credentials_options_set_max_tls_version_type grpc_tls_credentials_options_set_max_tls_version_import; -grpc_tls_credentials_options_copy_type grpc_tls_credentials_options_copy_import; -grpc_tls_credentials_options_destroy_type grpc_tls_credentials_options_destroy_import; -grpc_tls_credentials_options_set_certificate_provider_type grpc_tls_credentials_options_set_certificate_provider_import; -grpc_tls_credentials_options_watch_root_certs_type grpc_tls_credentials_options_watch_root_certs_import; -grpc_tls_credentials_options_set_root_cert_name_type grpc_tls_credentials_options_set_root_cert_name_import; -grpc_tls_credentials_options_watch_identity_key_cert_pairs_type grpc_tls_credentials_options_watch_identity_key_cert_pairs_import; -grpc_tls_credentials_options_set_identity_cert_name_type grpc_tls_credentials_options_set_identity_cert_name_import; -grpc_tls_credentials_options_set_cert_request_type_type grpc_tls_credentials_options_set_cert_request_type_import; -grpc_tls_credentials_options_set_crl_directory_type grpc_tls_credentials_options_set_crl_directory_import; -grpc_tls_credentials_options_set_verify_server_cert_type grpc_tls_credentials_options_set_verify_server_cert_import; -grpc_tls_credentials_options_set_send_client_ca_list_type grpc_tls_credentials_options_set_send_client_ca_list_import; -grpc_tls_credentials_options_set_check_call_host_type grpc_tls_credentials_options_set_check_call_host_import; -grpc_insecure_credentials_create_type grpc_insecure_credentials_create_import; -grpc_insecure_server_credentials_create_type grpc_insecure_server_credentials_create_import; -grpc_xds_credentials_create_type grpc_xds_credentials_create_import; -grpc_xds_server_credentials_create_type grpc_xds_server_credentials_create_import; grpc_authorization_policy_provider_static_data_create_type grpc_authorization_policy_provider_static_data_create_import; grpc_authorization_policy_provider_file_watcher_create_type grpc_authorization_policy_provider_file_watcher_create_import; grpc_authorization_policy_provider_release_type grpc_authorization_policy_provider_release_import; -grpc_tls_credentials_options_set_tls_session_key_log_file_path_type grpc_tls_credentials_options_set_tls_session_key_log_file_path_import; grpc_slice_ref_type grpc_slice_ref_import; grpc_slice_unref_type grpc_slice_unref_import; grpc_slice_copy_type grpc_slice_copy_import; @@ -332,6 +332,70 @@ void grpc_rb_load_imports(HMODULE library) { grpc_compression_options_enable_algorithm_import = (grpc_compression_options_enable_algorithm_type) GetProcAddress(library, "grpc_compression_options_enable_algorithm"); grpc_compression_options_disable_algorithm_import = (grpc_compression_options_disable_algorithm_type) GetProcAddress(library, "grpc_compression_options_disable_algorithm"); grpc_compression_options_is_algorithm_enabled_import = (grpc_compression_options_is_algorithm_enabled_type) GetProcAddress(library, "grpc_compression_options_is_algorithm_enabled"); + grpc_service_account_jwt_access_credentials_create_import = (grpc_service_account_jwt_access_credentials_create_type) GetProcAddress(library, "grpc_service_account_jwt_access_credentials_create"); + grpc_external_account_credentials_create_import = (grpc_external_account_credentials_create_type) GetProcAddress(library, "grpc_external_account_credentials_create"); + grpc_google_refresh_token_credentials_create_import = (grpc_google_refresh_token_credentials_create_type) GetProcAddress(library, "grpc_google_refresh_token_credentials_create"); + grpc_access_token_credentials_create_import = (grpc_access_token_credentials_create_type) GetProcAddress(library, "grpc_access_token_credentials_create"); + grpc_google_iam_credentials_create_import = (grpc_google_iam_credentials_create_type) GetProcAddress(library, "grpc_google_iam_credentials_create"); + grpc_sts_credentials_create_import = (grpc_sts_credentials_create_type) GetProcAddress(library, "grpc_sts_credentials_create"); + grpc_auth_metadata_context_copy_import = (grpc_auth_metadata_context_copy_type) GetProcAddress(library, "grpc_auth_metadata_context_copy"); + grpc_auth_metadata_context_reset_import = (grpc_auth_metadata_context_reset_type) GetProcAddress(library, "grpc_auth_metadata_context_reset"); + grpc_metadata_credentials_create_from_plugin_import = (grpc_metadata_credentials_create_from_plugin_type) GetProcAddress(library, "grpc_metadata_credentials_create_from_plugin"); + grpc_call_credentials_release_import = (grpc_call_credentials_release_type) GetProcAddress(library, "grpc_call_credentials_release"); + grpc_google_default_credentials_create_import = (grpc_google_default_credentials_create_type) GetProcAddress(library, "grpc_google_default_credentials_create"); + grpc_ssl_server_certificate_config_create_import = (grpc_ssl_server_certificate_config_create_type) GetProcAddress(library, "grpc_ssl_server_certificate_config_create"); + grpc_ssl_server_certificate_config_destroy_import = (grpc_ssl_server_certificate_config_destroy_type) GetProcAddress(library, "grpc_ssl_server_certificate_config_destroy"); + grpc_ssl_credentials_create_import = (grpc_ssl_credentials_create_type) GetProcAddress(library, "grpc_ssl_credentials_create"); + grpc_ssl_credentials_create_ex_import = (grpc_ssl_credentials_create_ex_type) GetProcAddress(library, "grpc_ssl_credentials_create_ex"); + grpc_ssl_server_credentials_create_import = (grpc_ssl_server_credentials_create_type) GetProcAddress(library, "grpc_ssl_server_credentials_create"); + grpc_ssl_server_credentials_create_ex_import = (grpc_ssl_server_credentials_create_ex_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_ex"); + grpc_ssl_server_credentials_create_options_using_config_import = (grpc_ssl_server_credentials_create_options_using_config_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_options_using_config"); + grpc_ssl_server_credentials_create_options_using_config_fetcher_import = (grpc_ssl_server_credentials_create_options_using_config_fetcher_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_options_using_config_fetcher"); + grpc_ssl_server_credentials_options_destroy_import = (grpc_ssl_server_credentials_options_destroy_type) GetProcAddress(library, "grpc_ssl_server_credentials_options_destroy"); + grpc_ssl_server_credentials_create_with_options_import = (grpc_ssl_server_credentials_create_with_options_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_with_options"); + grpc_server_credentials_set_auth_metadata_processor_import = (grpc_server_credentials_set_auth_metadata_processor_type) GetProcAddress(library, "grpc_server_credentials_set_auth_metadata_processor"); + grpc_composite_call_credentials_create_import = (grpc_composite_call_credentials_create_type) GetProcAddress(library, "grpc_composite_call_credentials_create"); + grpc_google_compute_engine_credentials_create_import = (grpc_google_compute_engine_credentials_create_type) GetProcAddress(library, "grpc_google_compute_engine_credentials_create"); + grpc_composite_channel_credentials_create_import = (grpc_composite_channel_credentials_create_type) GetProcAddress(library, "grpc_composite_channel_credentials_create"); + grpc_alts_credentials_client_options_create_import = (grpc_alts_credentials_client_options_create_type) GetProcAddress(library, "grpc_alts_credentials_client_options_create"); + grpc_alts_credentials_server_options_create_import = (grpc_alts_credentials_server_options_create_type) GetProcAddress(library, "grpc_alts_credentials_server_options_create"); + grpc_alts_credentials_client_options_add_target_service_account_import = (grpc_alts_credentials_client_options_add_target_service_account_type) GetProcAddress(library, "grpc_alts_credentials_client_options_add_target_service_account"); + grpc_alts_credentials_options_destroy_import = (grpc_alts_credentials_options_destroy_type) GetProcAddress(library, "grpc_alts_credentials_options_destroy"); + grpc_alts_credentials_create_import = (grpc_alts_credentials_create_type) GetProcAddress(library, "grpc_alts_credentials_create"); + grpc_alts_server_credentials_create_import = (grpc_alts_server_credentials_create_type) GetProcAddress(library, "grpc_alts_server_credentials_create"); + grpc_tls_identity_pairs_create_import = (grpc_tls_identity_pairs_create_type) GetProcAddress(library, "grpc_tls_identity_pairs_create"); + grpc_tls_identity_pairs_add_pair_import = (grpc_tls_identity_pairs_add_pair_type) GetProcAddress(library, "grpc_tls_identity_pairs_add_pair"); + grpc_tls_identity_pairs_destroy_import = (grpc_tls_identity_pairs_destroy_type) GetProcAddress(library, "grpc_tls_identity_pairs_destroy"); + grpc_tls_certificate_provider_static_data_create_import = (grpc_tls_certificate_provider_static_data_create_type) GetProcAddress(library, "grpc_tls_certificate_provider_static_data_create"); + grpc_tls_certificate_provider_file_watcher_create_import = (grpc_tls_certificate_provider_file_watcher_create_type) GetProcAddress(library, "grpc_tls_certificate_provider_file_watcher_create"); + grpc_tls_certificate_provider_release_import = (grpc_tls_certificate_provider_release_type) GetProcAddress(library, "grpc_tls_certificate_provider_release"); + grpc_tls_credentials_options_create_import = (grpc_tls_credentials_options_create_type) GetProcAddress(library, "grpc_tls_credentials_options_create"); + grpc_tls_credentials_options_set_min_tls_version_import = (grpc_tls_credentials_options_set_min_tls_version_type) GetProcAddress(library, "grpc_tls_credentials_options_set_min_tls_version"); + grpc_tls_credentials_options_set_max_tls_version_import = (grpc_tls_credentials_options_set_max_tls_version_type) GetProcAddress(library, "grpc_tls_credentials_options_set_max_tls_version"); + grpc_tls_credentials_options_copy_import = (grpc_tls_credentials_options_copy_type) GetProcAddress(library, "grpc_tls_credentials_options_copy"); + grpc_tls_credentials_options_destroy_import = (grpc_tls_credentials_options_destroy_type) GetProcAddress(library, "grpc_tls_credentials_options_destroy"); + grpc_tls_credentials_options_set_certificate_provider_import = (grpc_tls_credentials_options_set_certificate_provider_type) GetProcAddress(library, "grpc_tls_credentials_options_set_certificate_provider"); + grpc_tls_credentials_options_watch_root_certs_import = (grpc_tls_credentials_options_watch_root_certs_type) GetProcAddress(library, "grpc_tls_credentials_options_watch_root_certs"); + grpc_tls_credentials_options_set_root_cert_name_import = (grpc_tls_credentials_options_set_root_cert_name_type) GetProcAddress(library, "grpc_tls_credentials_options_set_root_cert_name"); + grpc_tls_credentials_options_watch_identity_key_cert_pairs_import = (grpc_tls_credentials_options_watch_identity_key_cert_pairs_type) GetProcAddress(library, "grpc_tls_credentials_options_watch_identity_key_cert_pairs"); + grpc_tls_credentials_options_set_identity_cert_name_import = (grpc_tls_credentials_options_set_identity_cert_name_type) GetProcAddress(library, "grpc_tls_credentials_options_set_identity_cert_name"); + grpc_tls_credentials_options_set_cert_request_type_import = (grpc_tls_credentials_options_set_cert_request_type_type) GetProcAddress(library, "grpc_tls_credentials_options_set_cert_request_type"); + grpc_tls_credentials_options_set_crl_directory_import = (grpc_tls_credentials_options_set_crl_directory_type) GetProcAddress(library, "grpc_tls_credentials_options_set_crl_directory"); + grpc_tls_credentials_options_set_verify_server_cert_import = (grpc_tls_credentials_options_set_verify_server_cert_type) GetProcAddress(library, "grpc_tls_credentials_options_set_verify_server_cert"); + grpc_tls_credentials_options_set_send_client_ca_list_import = (grpc_tls_credentials_options_set_send_client_ca_list_type) GetProcAddress(library, "grpc_tls_credentials_options_set_send_client_ca_list"); + grpc_ssl_session_cache_create_lru_import = (grpc_ssl_session_cache_create_lru_type) GetProcAddress(library, "grpc_ssl_session_cache_create_lru"); + grpc_ssl_session_cache_destroy_import = (grpc_ssl_session_cache_destroy_type) GetProcAddress(library, "grpc_ssl_session_cache_destroy"); + grpc_ssl_session_cache_create_channel_arg_import = (grpc_ssl_session_cache_create_channel_arg_type) GetProcAddress(library, "grpc_ssl_session_cache_create_channel_arg"); + grpc_set_ssl_roots_override_callback_import = (grpc_set_ssl_roots_override_callback_type) GetProcAddress(library, "grpc_set_ssl_roots_override_callback"); + grpc_max_auth_token_lifetime_import = (grpc_max_auth_token_lifetime_type) GetProcAddress(library, "grpc_max_auth_token_lifetime"); + grpc_insecure_credentials_create_import = (grpc_insecure_credentials_create_type) GetProcAddress(library, "grpc_insecure_credentials_create"); + grpc_insecure_server_credentials_create_import = (grpc_insecure_server_credentials_create_type) GetProcAddress(library, "grpc_insecure_server_credentials_create"); + grpc_xds_credentials_create_import = (grpc_xds_credentials_create_type) GetProcAddress(library, "grpc_xds_credentials_create"); + grpc_xds_server_credentials_create_import = (grpc_xds_server_credentials_create_type) GetProcAddress(library, "grpc_xds_server_credentials_create"); + grpc_local_credentials_create_import = (grpc_local_credentials_create_type) GetProcAddress(library, "grpc_local_credentials_create"); + grpc_local_server_credentials_create_import = (grpc_local_server_credentials_create_type) GetProcAddress(library, "grpc_local_server_credentials_create"); + grpc_tls_credentials_options_set_check_call_host_import = (grpc_tls_credentials_options_set_check_call_host_type) GetProcAddress(library, "grpc_tls_credentials_options_set_check_call_host"); + grpc_tls_credentials_options_set_tls_session_key_log_file_path_import = (grpc_tls_credentials_options_set_tls_session_key_log_file_path_type) GetProcAddress(library, "grpc_tls_credentials_options_set_tls_session_key_log_file_path"); grpc_metadata_array_init_import = (grpc_metadata_array_init_type) GetProcAddress(library, "grpc_metadata_array_init"); grpc_metadata_array_destroy_import = (grpc_metadata_array_destroy_type) GetProcAddress(library, "grpc_metadata_array_destroy"); grpc_call_details_init_import = (grpc_call_details_init_type) GetProcAddress(library, "grpc_call_details_init"); @@ -377,6 +441,7 @@ void grpc_rb_load_imports(HMODULE library) { grpc_call_failed_before_recv_message_import = (grpc_call_failed_before_recv_message_type) GetProcAddress(library, "grpc_call_failed_before_recv_message"); grpc_call_ref_import = (grpc_call_ref_type) GetProcAddress(library, "grpc_call_ref"); grpc_call_unref_import = (grpc_call_unref_type) GetProcAddress(library, "grpc_call_unref"); + grpc_call_set_credentials_import = (grpc_call_set_credentials_type) GetProcAddress(library, "grpc_call_set_credentials"); grpc_server_request_call_import = (grpc_server_request_call_type) GetProcAddress(library, "grpc_server_request_call"); grpc_server_register_method_import = (grpc_server_register_method_type) GetProcAddress(library, "grpc_server_register_method"); grpc_server_request_registered_call_import = (grpc_server_request_registered_call_type) GetProcAddress(library, "grpc_server_request_registered_call"); @@ -423,74 +488,9 @@ void grpc_rb_load_imports(HMODULE library) { grpc_auth_context_add_property_import = (grpc_auth_context_add_property_type) GetProcAddress(library, "grpc_auth_context_add_property"); grpc_auth_context_add_cstring_property_import = (grpc_auth_context_add_cstring_property_type) GetProcAddress(library, "grpc_auth_context_add_cstring_property"); grpc_auth_context_set_peer_identity_property_name_import = (grpc_auth_context_set_peer_identity_property_name_type) GetProcAddress(library, "grpc_auth_context_set_peer_identity_property_name"); - grpc_ssl_session_cache_create_lru_import = (grpc_ssl_session_cache_create_lru_type) GetProcAddress(library, "grpc_ssl_session_cache_create_lru"); - grpc_ssl_session_cache_destroy_import = (grpc_ssl_session_cache_destroy_type) GetProcAddress(library, "grpc_ssl_session_cache_destroy"); - grpc_ssl_session_cache_create_channel_arg_import = (grpc_ssl_session_cache_create_channel_arg_type) GetProcAddress(library, "grpc_ssl_session_cache_create_channel_arg"); - grpc_call_credentials_release_import = (grpc_call_credentials_release_type) GetProcAddress(library, "grpc_call_credentials_release"); - grpc_google_default_credentials_create_import = (grpc_google_default_credentials_create_type) GetProcAddress(library, "grpc_google_default_credentials_create"); - grpc_set_ssl_roots_override_callback_import = (grpc_set_ssl_roots_override_callback_type) GetProcAddress(library, "grpc_set_ssl_roots_override_callback"); - grpc_ssl_credentials_create_import = (grpc_ssl_credentials_create_type) GetProcAddress(library, "grpc_ssl_credentials_create"); - grpc_ssl_credentials_create_ex_import = (grpc_ssl_credentials_create_ex_type) GetProcAddress(library, "grpc_ssl_credentials_create_ex"); - grpc_composite_channel_credentials_create_import = (grpc_composite_channel_credentials_create_type) GetProcAddress(library, "grpc_composite_channel_credentials_create"); - grpc_composite_call_credentials_create_import = (grpc_composite_call_credentials_create_type) GetProcAddress(library, "grpc_composite_call_credentials_create"); - grpc_google_compute_engine_credentials_create_import = (grpc_google_compute_engine_credentials_create_type) GetProcAddress(library, "grpc_google_compute_engine_credentials_create"); - grpc_max_auth_token_lifetime_import = (grpc_max_auth_token_lifetime_type) GetProcAddress(library, "grpc_max_auth_token_lifetime"); - grpc_service_account_jwt_access_credentials_create_import = (grpc_service_account_jwt_access_credentials_create_type) GetProcAddress(library, "grpc_service_account_jwt_access_credentials_create"); - grpc_external_account_credentials_create_import = (grpc_external_account_credentials_create_type) GetProcAddress(library, "grpc_external_account_credentials_create"); - grpc_google_refresh_token_credentials_create_import = (grpc_google_refresh_token_credentials_create_type) GetProcAddress(library, "grpc_google_refresh_token_credentials_create"); - grpc_access_token_credentials_create_import = (grpc_access_token_credentials_create_type) GetProcAddress(library, "grpc_access_token_credentials_create"); - grpc_google_iam_credentials_create_import = (grpc_google_iam_credentials_create_type) GetProcAddress(library, "grpc_google_iam_credentials_create"); - grpc_sts_credentials_create_import = (grpc_sts_credentials_create_type) GetProcAddress(library, "grpc_sts_credentials_create"); - grpc_auth_metadata_context_copy_import = (grpc_auth_metadata_context_copy_type) GetProcAddress(library, "grpc_auth_metadata_context_copy"); - grpc_auth_metadata_context_reset_import = (grpc_auth_metadata_context_reset_type) GetProcAddress(library, "grpc_auth_metadata_context_reset"); - grpc_metadata_credentials_create_from_plugin_import = (grpc_metadata_credentials_create_from_plugin_type) GetProcAddress(library, "grpc_metadata_credentials_create_from_plugin"); - grpc_ssl_server_certificate_config_create_import = (grpc_ssl_server_certificate_config_create_type) GetProcAddress(library, "grpc_ssl_server_certificate_config_create"); - grpc_ssl_server_certificate_config_destroy_import = (grpc_ssl_server_certificate_config_destroy_type) GetProcAddress(library, "grpc_ssl_server_certificate_config_destroy"); - grpc_ssl_server_credentials_create_import = (grpc_ssl_server_credentials_create_type) GetProcAddress(library, "grpc_ssl_server_credentials_create"); - grpc_ssl_server_credentials_create_ex_import = (grpc_ssl_server_credentials_create_ex_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_ex"); - grpc_ssl_server_credentials_create_options_using_config_import = (grpc_ssl_server_credentials_create_options_using_config_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_options_using_config"); - grpc_ssl_server_credentials_create_options_using_config_fetcher_import = (grpc_ssl_server_credentials_create_options_using_config_fetcher_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_options_using_config_fetcher"); - grpc_ssl_server_credentials_options_destroy_import = (grpc_ssl_server_credentials_options_destroy_type) GetProcAddress(library, "grpc_ssl_server_credentials_options_destroy"); - grpc_ssl_server_credentials_create_with_options_import = (grpc_ssl_server_credentials_create_with_options_type) GetProcAddress(library, "grpc_ssl_server_credentials_create_with_options"); - grpc_call_set_credentials_import = (grpc_call_set_credentials_type) GetProcAddress(library, "grpc_call_set_credentials"); - grpc_server_credentials_set_auth_metadata_processor_import = (grpc_server_credentials_set_auth_metadata_processor_type) GetProcAddress(library, "grpc_server_credentials_set_auth_metadata_processor"); - grpc_alts_credentials_client_options_create_import = (grpc_alts_credentials_client_options_create_type) GetProcAddress(library, "grpc_alts_credentials_client_options_create"); - grpc_alts_credentials_server_options_create_import = (grpc_alts_credentials_server_options_create_type) GetProcAddress(library, "grpc_alts_credentials_server_options_create"); - grpc_alts_credentials_client_options_add_target_service_account_import = (grpc_alts_credentials_client_options_add_target_service_account_type) GetProcAddress(library, "grpc_alts_credentials_client_options_add_target_service_account"); - grpc_alts_credentials_options_destroy_import = (grpc_alts_credentials_options_destroy_type) GetProcAddress(library, "grpc_alts_credentials_options_destroy"); - grpc_alts_credentials_create_import = (grpc_alts_credentials_create_type) GetProcAddress(library, "grpc_alts_credentials_create"); - grpc_alts_server_credentials_create_import = (grpc_alts_server_credentials_create_type) GetProcAddress(library, "grpc_alts_server_credentials_create"); - grpc_local_credentials_create_import = (grpc_local_credentials_create_type) GetProcAddress(library, "grpc_local_credentials_create"); - grpc_local_server_credentials_create_import = (grpc_local_server_credentials_create_type) GetProcAddress(library, "grpc_local_server_credentials_create"); - grpc_tls_identity_pairs_create_import = (grpc_tls_identity_pairs_create_type) GetProcAddress(library, "grpc_tls_identity_pairs_create"); - grpc_tls_identity_pairs_add_pair_import = (grpc_tls_identity_pairs_add_pair_type) GetProcAddress(library, "grpc_tls_identity_pairs_add_pair"); - grpc_tls_identity_pairs_destroy_import = (grpc_tls_identity_pairs_destroy_type) GetProcAddress(library, "grpc_tls_identity_pairs_destroy"); - grpc_tls_certificate_provider_static_data_create_import = (grpc_tls_certificate_provider_static_data_create_type) GetProcAddress(library, "grpc_tls_certificate_provider_static_data_create"); - grpc_tls_certificate_provider_file_watcher_create_import = (grpc_tls_certificate_provider_file_watcher_create_type) GetProcAddress(library, "grpc_tls_certificate_provider_file_watcher_create"); - grpc_tls_certificate_provider_release_import = (grpc_tls_certificate_provider_release_type) GetProcAddress(library, "grpc_tls_certificate_provider_release"); - grpc_tls_credentials_options_create_import = (grpc_tls_credentials_options_create_type) GetProcAddress(library, "grpc_tls_credentials_options_create"); - grpc_tls_credentials_options_set_min_tls_version_import = (grpc_tls_credentials_options_set_min_tls_version_type) GetProcAddress(library, "grpc_tls_credentials_options_set_min_tls_version"); - grpc_tls_credentials_options_set_max_tls_version_import = (grpc_tls_credentials_options_set_max_tls_version_type) GetProcAddress(library, "grpc_tls_credentials_options_set_max_tls_version"); - grpc_tls_credentials_options_copy_import = (grpc_tls_credentials_options_copy_type) GetProcAddress(library, "grpc_tls_credentials_options_copy"); - grpc_tls_credentials_options_destroy_import = (grpc_tls_credentials_options_destroy_type) GetProcAddress(library, "grpc_tls_credentials_options_destroy"); - grpc_tls_credentials_options_set_certificate_provider_import = (grpc_tls_credentials_options_set_certificate_provider_type) GetProcAddress(library, "grpc_tls_credentials_options_set_certificate_provider"); - grpc_tls_credentials_options_watch_root_certs_import = (grpc_tls_credentials_options_watch_root_certs_type) GetProcAddress(library, "grpc_tls_credentials_options_watch_root_certs"); - grpc_tls_credentials_options_set_root_cert_name_import = (grpc_tls_credentials_options_set_root_cert_name_type) GetProcAddress(library, "grpc_tls_credentials_options_set_root_cert_name"); - grpc_tls_credentials_options_watch_identity_key_cert_pairs_import = (grpc_tls_credentials_options_watch_identity_key_cert_pairs_type) GetProcAddress(library, "grpc_tls_credentials_options_watch_identity_key_cert_pairs"); - grpc_tls_credentials_options_set_identity_cert_name_import = (grpc_tls_credentials_options_set_identity_cert_name_type) GetProcAddress(library, "grpc_tls_credentials_options_set_identity_cert_name"); - grpc_tls_credentials_options_set_cert_request_type_import = (grpc_tls_credentials_options_set_cert_request_type_type) GetProcAddress(library, "grpc_tls_credentials_options_set_cert_request_type"); - grpc_tls_credentials_options_set_crl_directory_import = (grpc_tls_credentials_options_set_crl_directory_type) GetProcAddress(library, "grpc_tls_credentials_options_set_crl_directory"); - grpc_tls_credentials_options_set_verify_server_cert_import = (grpc_tls_credentials_options_set_verify_server_cert_type) GetProcAddress(library, "grpc_tls_credentials_options_set_verify_server_cert"); - grpc_tls_credentials_options_set_send_client_ca_list_import = (grpc_tls_credentials_options_set_send_client_ca_list_type) GetProcAddress(library, "grpc_tls_credentials_options_set_send_client_ca_list"); - grpc_tls_credentials_options_set_check_call_host_import = (grpc_tls_credentials_options_set_check_call_host_type) GetProcAddress(library, "grpc_tls_credentials_options_set_check_call_host"); - grpc_insecure_credentials_create_import = (grpc_insecure_credentials_create_type) GetProcAddress(library, "grpc_insecure_credentials_create"); - grpc_insecure_server_credentials_create_import = (grpc_insecure_server_credentials_create_type) GetProcAddress(library, "grpc_insecure_server_credentials_create"); - grpc_xds_credentials_create_import = (grpc_xds_credentials_create_type) GetProcAddress(library, "grpc_xds_credentials_create"); - grpc_xds_server_credentials_create_import = (grpc_xds_server_credentials_create_type) GetProcAddress(library, "grpc_xds_server_credentials_create"); grpc_authorization_policy_provider_static_data_create_import = (grpc_authorization_policy_provider_static_data_create_type) GetProcAddress(library, "grpc_authorization_policy_provider_static_data_create"); grpc_authorization_policy_provider_file_watcher_create_import = (grpc_authorization_policy_provider_file_watcher_create_type) GetProcAddress(library, "grpc_authorization_policy_provider_file_watcher_create"); grpc_authorization_policy_provider_release_import = (grpc_authorization_policy_provider_release_type) GetProcAddress(library, "grpc_authorization_policy_provider_release"); - grpc_tls_credentials_options_set_tls_session_key_log_file_path_import = (grpc_tls_credentials_options_set_tls_session_key_log_file_path_type) GetProcAddress(library, "grpc_tls_credentials_options_set_tls_session_key_log_file_path"); grpc_slice_ref_import = (grpc_slice_ref_type) GetProcAddress(library, "grpc_slice_ref"); grpc_slice_unref_import = (grpc_slice_unref_type) GetProcAddress(library, "grpc_slice_unref"); grpc_slice_copy_import = (grpc_slice_copy_type) GetProcAddress(library, "grpc_slice_copy"); diff --git a/src/ruby/ext/grpc/rb_grpc_imports.generated.h b/src/ruby/ext/grpc/rb_grpc_imports.generated.h index d4e2099eda4..42fb67dface 100644 --- a/src/ruby/ext/grpc/rb_grpc_imports.generated.h +++ b/src/ruby/ext/grpc/rb_grpc_imports.generated.h @@ -27,6 +27,7 @@ #include #include +#include #include #include #include @@ -101,6 +102,198 @@ extern grpc_compression_options_disable_algorithm_type grpc_compression_options_ typedef int(*grpc_compression_options_is_algorithm_enabled_type)(const grpc_compression_options* opts, grpc_compression_algorithm algorithm); extern grpc_compression_options_is_algorithm_enabled_type grpc_compression_options_is_algorithm_enabled_import; #define grpc_compression_options_is_algorithm_enabled grpc_compression_options_is_algorithm_enabled_import +typedef grpc_call_credentials*(*grpc_service_account_jwt_access_credentials_create_type)(const char* json_key, gpr_timespec token_lifetime, void* reserved); +extern grpc_service_account_jwt_access_credentials_create_type grpc_service_account_jwt_access_credentials_create_import; +#define grpc_service_account_jwt_access_credentials_create grpc_service_account_jwt_access_credentials_create_import +typedef grpc_call_credentials*(*grpc_external_account_credentials_create_type)(const char* json_string, const char* scopes_string); +extern grpc_external_account_credentials_create_type grpc_external_account_credentials_create_import; +#define grpc_external_account_credentials_create grpc_external_account_credentials_create_import +typedef grpc_call_credentials*(*grpc_google_refresh_token_credentials_create_type)(const char* json_refresh_token, void* reserved); +extern grpc_google_refresh_token_credentials_create_type grpc_google_refresh_token_credentials_create_import; +#define grpc_google_refresh_token_credentials_create grpc_google_refresh_token_credentials_create_import +typedef grpc_call_credentials*(*grpc_access_token_credentials_create_type)(const char* access_token, void* reserved); +extern grpc_access_token_credentials_create_type grpc_access_token_credentials_create_import; +#define grpc_access_token_credentials_create grpc_access_token_credentials_create_import +typedef grpc_call_credentials*(*grpc_google_iam_credentials_create_type)(const char* authorization_token, const char* authority_selector, void* reserved); +extern grpc_google_iam_credentials_create_type grpc_google_iam_credentials_create_import; +#define grpc_google_iam_credentials_create grpc_google_iam_credentials_create_import +typedef grpc_call_credentials*(*grpc_sts_credentials_create_type)(const grpc_sts_credentials_options* options, void* reserved); +extern grpc_sts_credentials_create_type grpc_sts_credentials_create_import; +#define grpc_sts_credentials_create grpc_sts_credentials_create_import +typedef void(*grpc_auth_metadata_context_copy_type)(grpc_auth_metadata_context* from, grpc_auth_metadata_context* to); +extern grpc_auth_metadata_context_copy_type grpc_auth_metadata_context_copy_import; +#define grpc_auth_metadata_context_copy grpc_auth_metadata_context_copy_import +typedef void(*grpc_auth_metadata_context_reset_type)(grpc_auth_metadata_context* context); +extern grpc_auth_metadata_context_reset_type grpc_auth_metadata_context_reset_import; +#define grpc_auth_metadata_context_reset grpc_auth_metadata_context_reset_import +typedef grpc_call_credentials*(*grpc_metadata_credentials_create_from_plugin_type)(grpc_metadata_credentials_plugin plugin, grpc_security_level min_security_level, void* reserved); +extern grpc_metadata_credentials_create_from_plugin_type grpc_metadata_credentials_create_from_plugin_import; +#define grpc_metadata_credentials_create_from_plugin grpc_metadata_credentials_create_from_plugin_import +typedef void(*grpc_call_credentials_release_type)(grpc_call_credentials* creds); +extern grpc_call_credentials_release_type grpc_call_credentials_release_import; +#define grpc_call_credentials_release grpc_call_credentials_release_import +typedef grpc_channel_credentials*(*grpc_google_default_credentials_create_type)(grpc_call_credentials* call_credentials); +extern grpc_google_default_credentials_create_type grpc_google_default_credentials_create_import; +#define grpc_google_default_credentials_create grpc_google_default_credentials_create_import +typedef grpc_ssl_server_certificate_config*(*grpc_ssl_server_certificate_config_create_type)(const char* pem_root_certs, const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs); +extern grpc_ssl_server_certificate_config_create_type grpc_ssl_server_certificate_config_create_import; +#define grpc_ssl_server_certificate_config_create grpc_ssl_server_certificate_config_create_import +typedef void(*grpc_ssl_server_certificate_config_destroy_type)(grpc_ssl_server_certificate_config* config); +extern grpc_ssl_server_certificate_config_destroy_type grpc_ssl_server_certificate_config_destroy_import; +#define grpc_ssl_server_certificate_config_destroy grpc_ssl_server_certificate_config_destroy_import +typedef grpc_channel_credentials*(*grpc_ssl_credentials_create_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const verify_peer_options* verify_options, void* reserved); +extern grpc_ssl_credentials_create_type grpc_ssl_credentials_create_import; +#define grpc_ssl_credentials_create grpc_ssl_credentials_create_import +typedef grpc_channel_credentials*(*grpc_ssl_credentials_create_ex_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const grpc_ssl_verify_peer_options* verify_options, void* reserved); +extern grpc_ssl_credentials_create_ex_type grpc_ssl_credentials_create_ex_import; +#define grpc_ssl_credentials_create_ex grpc_ssl_credentials_create_ex_import +typedef grpc_server_credentials*(*grpc_ssl_server_credentials_create_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, int force_client_auth, void* reserved); +extern grpc_ssl_server_credentials_create_type grpc_ssl_server_credentials_create_import; +#define grpc_ssl_server_credentials_create grpc_ssl_server_credentials_create_import +typedef grpc_server_credentials*(*grpc_ssl_server_credentials_create_ex_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, grpc_ssl_client_certificate_request_type client_certificate_request, void* reserved); +extern grpc_ssl_server_credentials_create_ex_type grpc_ssl_server_credentials_create_ex_import; +#define grpc_ssl_server_credentials_create_ex grpc_ssl_server_credentials_create_ex_import +typedef grpc_ssl_server_credentials_options*(*grpc_ssl_server_credentials_create_options_using_config_type)(grpc_ssl_client_certificate_request_type client_certificate_request, grpc_ssl_server_certificate_config* certificate_config); +extern grpc_ssl_server_credentials_create_options_using_config_type grpc_ssl_server_credentials_create_options_using_config_import; +#define grpc_ssl_server_credentials_create_options_using_config grpc_ssl_server_credentials_create_options_using_config_import +typedef grpc_ssl_server_credentials_options*(*grpc_ssl_server_credentials_create_options_using_config_fetcher_type)(grpc_ssl_client_certificate_request_type client_certificate_request, grpc_ssl_server_certificate_config_callback cb, void* user_data); +extern grpc_ssl_server_credentials_create_options_using_config_fetcher_type grpc_ssl_server_credentials_create_options_using_config_fetcher_import; +#define grpc_ssl_server_credentials_create_options_using_config_fetcher grpc_ssl_server_credentials_create_options_using_config_fetcher_import +typedef void(*grpc_ssl_server_credentials_options_destroy_type)(grpc_ssl_server_credentials_options* options); +extern grpc_ssl_server_credentials_options_destroy_type grpc_ssl_server_credentials_options_destroy_import; +#define grpc_ssl_server_credentials_options_destroy grpc_ssl_server_credentials_options_destroy_import +typedef grpc_server_credentials*(*grpc_ssl_server_credentials_create_with_options_type)(grpc_ssl_server_credentials_options* options); +extern grpc_ssl_server_credentials_create_with_options_type grpc_ssl_server_credentials_create_with_options_import; +#define grpc_ssl_server_credentials_create_with_options grpc_ssl_server_credentials_create_with_options_import +typedef void(*grpc_server_credentials_set_auth_metadata_processor_type)(grpc_server_credentials* creds, grpc_auth_metadata_processor processor); +extern grpc_server_credentials_set_auth_metadata_processor_type grpc_server_credentials_set_auth_metadata_processor_import; +#define grpc_server_credentials_set_auth_metadata_processor grpc_server_credentials_set_auth_metadata_processor_import +typedef grpc_call_credentials*(*grpc_composite_call_credentials_create_type)(grpc_call_credentials* creds1, grpc_call_credentials* creds2, void* reserved); +extern grpc_composite_call_credentials_create_type grpc_composite_call_credentials_create_import; +#define grpc_composite_call_credentials_create grpc_composite_call_credentials_create_import +typedef grpc_call_credentials*(*grpc_google_compute_engine_credentials_create_type)(void* reserved); +extern grpc_google_compute_engine_credentials_create_type grpc_google_compute_engine_credentials_create_import; +#define grpc_google_compute_engine_credentials_create grpc_google_compute_engine_credentials_create_import +typedef grpc_channel_credentials*(*grpc_composite_channel_credentials_create_type)(grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds, void* reserved); +extern grpc_composite_channel_credentials_create_type grpc_composite_channel_credentials_create_import; +#define grpc_composite_channel_credentials_create grpc_composite_channel_credentials_create_import +typedef grpc_alts_credentials_options*(*grpc_alts_credentials_client_options_create_type)(void); +extern grpc_alts_credentials_client_options_create_type grpc_alts_credentials_client_options_create_import; +#define grpc_alts_credentials_client_options_create grpc_alts_credentials_client_options_create_import +typedef grpc_alts_credentials_options*(*grpc_alts_credentials_server_options_create_type)(void); +extern grpc_alts_credentials_server_options_create_type grpc_alts_credentials_server_options_create_import; +#define grpc_alts_credentials_server_options_create grpc_alts_credentials_server_options_create_import +typedef void(*grpc_alts_credentials_client_options_add_target_service_account_type)(grpc_alts_credentials_options* options, const char* service_account); +extern grpc_alts_credentials_client_options_add_target_service_account_type grpc_alts_credentials_client_options_add_target_service_account_import; +#define grpc_alts_credentials_client_options_add_target_service_account grpc_alts_credentials_client_options_add_target_service_account_import +typedef void(*grpc_alts_credentials_options_destroy_type)(grpc_alts_credentials_options* options); +extern grpc_alts_credentials_options_destroy_type grpc_alts_credentials_options_destroy_import; +#define grpc_alts_credentials_options_destroy grpc_alts_credentials_options_destroy_import +typedef grpc_channel_credentials*(*grpc_alts_credentials_create_type)(const grpc_alts_credentials_options* options); +extern grpc_alts_credentials_create_type grpc_alts_credentials_create_import; +#define grpc_alts_credentials_create grpc_alts_credentials_create_import +typedef grpc_server_credentials*(*grpc_alts_server_credentials_create_type)(const grpc_alts_credentials_options* options); +extern grpc_alts_server_credentials_create_type grpc_alts_server_credentials_create_import; +#define grpc_alts_server_credentials_create grpc_alts_server_credentials_create_import +typedef grpc_tls_identity_pairs*(*grpc_tls_identity_pairs_create_type)(); +extern grpc_tls_identity_pairs_create_type grpc_tls_identity_pairs_create_import; +#define grpc_tls_identity_pairs_create grpc_tls_identity_pairs_create_import +typedef void(*grpc_tls_identity_pairs_add_pair_type)(grpc_tls_identity_pairs* pairs, const char* private_key, const char* cert_chain); +extern grpc_tls_identity_pairs_add_pair_type grpc_tls_identity_pairs_add_pair_import; +#define grpc_tls_identity_pairs_add_pair grpc_tls_identity_pairs_add_pair_import +typedef void(*grpc_tls_identity_pairs_destroy_type)(grpc_tls_identity_pairs* pairs); +extern grpc_tls_identity_pairs_destroy_type grpc_tls_identity_pairs_destroy_import; +#define grpc_tls_identity_pairs_destroy grpc_tls_identity_pairs_destroy_import +typedef grpc_tls_certificate_provider*(*grpc_tls_certificate_provider_static_data_create_type)(const char* root_certificate, grpc_tls_identity_pairs* pem_key_cert_pairs); +extern grpc_tls_certificate_provider_static_data_create_type grpc_tls_certificate_provider_static_data_create_import; +#define grpc_tls_certificate_provider_static_data_create grpc_tls_certificate_provider_static_data_create_import +typedef grpc_tls_certificate_provider*(*grpc_tls_certificate_provider_file_watcher_create_type)(const char* private_key_path, const char* identity_certificate_path, const char* root_cert_path, unsigned int refresh_interval_sec); +extern grpc_tls_certificate_provider_file_watcher_create_type grpc_tls_certificate_provider_file_watcher_create_import; +#define grpc_tls_certificate_provider_file_watcher_create grpc_tls_certificate_provider_file_watcher_create_import +typedef void(*grpc_tls_certificate_provider_release_type)(grpc_tls_certificate_provider* provider); +extern grpc_tls_certificate_provider_release_type grpc_tls_certificate_provider_release_import; +#define grpc_tls_certificate_provider_release grpc_tls_certificate_provider_release_import +typedef grpc_tls_credentials_options*(*grpc_tls_credentials_options_create_type)(void); +extern grpc_tls_credentials_options_create_type grpc_tls_credentials_options_create_import; +#define grpc_tls_credentials_options_create grpc_tls_credentials_options_create_import +typedef void(*grpc_tls_credentials_options_set_min_tls_version_type)(grpc_tls_credentials_options* options, grpc_tls_version min_tls_version); +extern grpc_tls_credentials_options_set_min_tls_version_type grpc_tls_credentials_options_set_min_tls_version_import; +#define grpc_tls_credentials_options_set_min_tls_version grpc_tls_credentials_options_set_min_tls_version_import +typedef void(*grpc_tls_credentials_options_set_max_tls_version_type)(grpc_tls_credentials_options* options, grpc_tls_version max_tls_version); +extern grpc_tls_credentials_options_set_max_tls_version_type grpc_tls_credentials_options_set_max_tls_version_import; +#define grpc_tls_credentials_options_set_max_tls_version grpc_tls_credentials_options_set_max_tls_version_import +typedef grpc_tls_credentials_options*(*grpc_tls_credentials_options_copy_type)(grpc_tls_credentials_options* options); +extern grpc_tls_credentials_options_copy_type grpc_tls_credentials_options_copy_import; +#define grpc_tls_credentials_options_copy grpc_tls_credentials_options_copy_import +typedef void(*grpc_tls_credentials_options_destroy_type)(grpc_tls_credentials_options* options); +extern grpc_tls_credentials_options_destroy_type grpc_tls_credentials_options_destroy_import; +#define grpc_tls_credentials_options_destroy grpc_tls_credentials_options_destroy_import +typedef void(*grpc_tls_credentials_options_set_certificate_provider_type)(grpc_tls_credentials_options* options, grpc_tls_certificate_provider* provider); +extern grpc_tls_credentials_options_set_certificate_provider_type grpc_tls_credentials_options_set_certificate_provider_import; +#define grpc_tls_credentials_options_set_certificate_provider grpc_tls_credentials_options_set_certificate_provider_import +typedef void(*grpc_tls_credentials_options_watch_root_certs_type)(grpc_tls_credentials_options* options); +extern grpc_tls_credentials_options_watch_root_certs_type grpc_tls_credentials_options_watch_root_certs_import; +#define grpc_tls_credentials_options_watch_root_certs grpc_tls_credentials_options_watch_root_certs_import +typedef void(*grpc_tls_credentials_options_set_root_cert_name_type)(grpc_tls_credentials_options* options, const char* root_cert_name); +extern grpc_tls_credentials_options_set_root_cert_name_type grpc_tls_credentials_options_set_root_cert_name_import; +#define grpc_tls_credentials_options_set_root_cert_name grpc_tls_credentials_options_set_root_cert_name_import +typedef void(*grpc_tls_credentials_options_watch_identity_key_cert_pairs_type)(grpc_tls_credentials_options* options); +extern grpc_tls_credentials_options_watch_identity_key_cert_pairs_type grpc_tls_credentials_options_watch_identity_key_cert_pairs_import; +#define grpc_tls_credentials_options_watch_identity_key_cert_pairs grpc_tls_credentials_options_watch_identity_key_cert_pairs_import +typedef void(*grpc_tls_credentials_options_set_identity_cert_name_type)(grpc_tls_credentials_options* options, const char* identity_cert_name); +extern grpc_tls_credentials_options_set_identity_cert_name_type grpc_tls_credentials_options_set_identity_cert_name_import; +#define grpc_tls_credentials_options_set_identity_cert_name grpc_tls_credentials_options_set_identity_cert_name_import +typedef void(*grpc_tls_credentials_options_set_cert_request_type_type)(grpc_tls_credentials_options* options, grpc_ssl_client_certificate_request_type type); +extern grpc_tls_credentials_options_set_cert_request_type_type grpc_tls_credentials_options_set_cert_request_type_import; +#define grpc_tls_credentials_options_set_cert_request_type grpc_tls_credentials_options_set_cert_request_type_import +typedef void(*grpc_tls_credentials_options_set_crl_directory_type)(grpc_tls_credentials_options* options, const char* crl_directory); +extern grpc_tls_credentials_options_set_crl_directory_type grpc_tls_credentials_options_set_crl_directory_import; +#define grpc_tls_credentials_options_set_crl_directory grpc_tls_credentials_options_set_crl_directory_import +typedef void(*grpc_tls_credentials_options_set_verify_server_cert_type)(grpc_tls_credentials_options* options, int verify_server_cert); +extern grpc_tls_credentials_options_set_verify_server_cert_type grpc_tls_credentials_options_set_verify_server_cert_import; +#define grpc_tls_credentials_options_set_verify_server_cert grpc_tls_credentials_options_set_verify_server_cert_import +typedef void(*grpc_tls_credentials_options_set_send_client_ca_list_type)(grpc_tls_credentials_options* options, bool send_client_ca_list); +extern grpc_tls_credentials_options_set_send_client_ca_list_type grpc_tls_credentials_options_set_send_client_ca_list_import; +#define grpc_tls_credentials_options_set_send_client_ca_list grpc_tls_credentials_options_set_send_client_ca_list_import +typedef grpc_ssl_session_cache*(*grpc_ssl_session_cache_create_lru_type)(size_t capacity); +extern grpc_ssl_session_cache_create_lru_type grpc_ssl_session_cache_create_lru_import; +#define grpc_ssl_session_cache_create_lru grpc_ssl_session_cache_create_lru_import +typedef void(*grpc_ssl_session_cache_destroy_type)(grpc_ssl_session_cache* cache); +extern grpc_ssl_session_cache_destroy_type grpc_ssl_session_cache_destroy_import; +#define grpc_ssl_session_cache_destroy grpc_ssl_session_cache_destroy_import +typedef grpc_arg(*grpc_ssl_session_cache_create_channel_arg_type)(grpc_ssl_session_cache* cache); +extern grpc_ssl_session_cache_create_channel_arg_type grpc_ssl_session_cache_create_channel_arg_import; +#define grpc_ssl_session_cache_create_channel_arg grpc_ssl_session_cache_create_channel_arg_import +typedef void(*grpc_set_ssl_roots_override_callback_type)(grpc_ssl_roots_override_callback cb); +extern grpc_set_ssl_roots_override_callback_type grpc_set_ssl_roots_override_callback_import; +#define grpc_set_ssl_roots_override_callback grpc_set_ssl_roots_override_callback_import +typedef gpr_timespec(*grpc_max_auth_token_lifetime_type)(void); +extern grpc_max_auth_token_lifetime_type grpc_max_auth_token_lifetime_import; +#define grpc_max_auth_token_lifetime grpc_max_auth_token_lifetime_import +typedef grpc_channel_credentials*(*grpc_insecure_credentials_create_type)(); +extern grpc_insecure_credentials_create_type grpc_insecure_credentials_create_import; +#define grpc_insecure_credentials_create grpc_insecure_credentials_create_import +typedef grpc_server_credentials*(*grpc_insecure_server_credentials_create_type)(); +extern grpc_insecure_server_credentials_create_type grpc_insecure_server_credentials_create_import; +#define grpc_insecure_server_credentials_create grpc_insecure_server_credentials_create_import +typedef grpc_channel_credentials*(*grpc_xds_credentials_create_type)(grpc_channel_credentials* fallback_credentials); +extern grpc_xds_credentials_create_type grpc_xds_credentials_create_import; +#define grpc_xds_credentials_create grpc_xds_credentials_create_import +typedef grpc_server_credentials*(*grpc_xds_server_credentials_create_type)(grpc_server_credentials* fallback_credentials); +extern grpc_xds_server_credentials_create_type grpc_xds_server_credentials_create_import; +#define grpc_xds_server_credentials_create grpc_xds_server_credentials_create_import +typedef grpc_channel_credentials*(*grpc_local_credentials_create_type)(grpc_local_connect_type type); +extern grpc_local_credentials_create_type grpc_local_credentials_create_import; +#define grpc_local_credentials_create grpc_local_credentials_create_import +typedef grpc_server_credentials*(*grpc_local_server_credentials_create_type)(grpc_local_connect_type type); +extern grpc_local_server_credentials_create_type grpc_local_server_credentials_create_import; +#define grpc_local_server_credentials_create grpc_local_server_credentials_create_import +typedef void(*grpc_tls_credentials_options_set_check_call_host_type)(grpc_tls_credentials_options* options, int check_call_host); +extern grpc_tls_credentials_options_set_check_call_host_type grpc_tls_credentials_options_set_check_call_host_import; +#define grpc_tls_credentials_options_set_check_call_host grpc_tls_credentials_options_set_check_call_host_import +typedef void(*grpc_tls_credentials_options_set_tls_session_key_log_file_path_type)(grpc_tls_credentials_options* options, const char* path); +extern grpc_tls_credentials_options_set_tls_session_key_log_file_path_type grpc_tls_credentials_options_set_tls_session_key_log_file_path_import; +#define grpc_tls_credentials_options_set_tls_session_key_log_file_path grpc_tls_credentials_options_set_tls_session_key_log_file_path_import typedef void(*grpc_metadata_array_init_type)(grpc_metadata_array* array); extern grpc_metadata_array_init_type grpc_metadata_array_init_import; #define grpc_metadata_array_init grpc_metadata_array_init_import @@ -236,6 +429,9 @@ extern grpc_call_ref_type grpc_call_ref_import; typedef void(*grpc_call_unref_type)(grpc_call* call); extern grpc_call_unref_type grpc_call_unref_import; #define grpc_call_unref grpc_call_unref_import +typedef grpc_call_error(*grpc_call_set_credentials_type)(grpc_call* call, grpc_call_credentials* creds); +extern grpc_call_set_credentials_type grpc_call_set_credentials_import; +#define grpc_call_set_credentials grpc_call_set_credentials_import typedef grpc_call_error(*grpc_server_request_call_type)(grpc_server* server, grpc_call** call, grpc_call_details* details, grpc_metadata_array* request_metadata, grpc_completion_queue* cq_bound_to_call, grpc_completion_queue* cq_for_notification, void* tag_new); extern grpc_server_request_call_type grpc_server_request_call_import; #define grpc_server_request_call grpc_server_request_call_import @@ -374,198 +570,6 @@ extern grpc_auth_context_add_cstring_property_type grpc_auth_context_add_cstring typedef int(*grpc_auth_context_set_peer_identity_property_name_type)(grpc_auth_context* ctx, const char* name); extern grpc_auth_context_set_peer_identity_property_name_type grpc_auth_context_set_peer_identity_property_name_import; #define grpc_auth_context_set_peer_identity_property_name grpc_auth_context_set_peer_identity_property_name_import -typedef grpc_ssl_session_cache*(*grpc_ssl_session_cache_create_lru_type)(size_t capacity); -extern grpc_ssl_session_cache_create_lru_type grpc_ssl_session_cache_create_lru_import; -#define grpc_ssl_session_cache_create_lru grpc_ssl_session_cache_create_lru_import -typedef void(*grpc_ssl_session_cache_destroy_type)(grpc_ssl_session_cache* cache); -extern grpc_ssl_session_cache_destroy_type grpc_ssl_session_cache_destroy_import; -#define grpc_ssl_session_cache_destroy grpc_ssl_session_cache_destroy_import -typedef grpc_arg(*grpc_ssl_session_cache_create_channel_arg_type)(grpc_ssl_session_cache* cache); -extern grpc_ssl_session_cache_create_channel_arg_type grpc_ssl_session_cache_create_channel_arg_import; -#define grpc_ssl_session_cache_create_channel_arg grpc_ssl_session_cache_create_channel_arg_import -typedef void(*grpc_call_credentials_release_type)(grpc_call_credentials* creds); -extern grpc_call_credentials_release_type grpc_call_credentials_release_import; -#define grpc_call_credentials_release grpc_call_credentials_release_import -typedef grpc_channel_credentials*(*grpc_google_default_credentials_create_type)(grpc_call_credentials* call_credentials); -extern grpc_google_default_credentials_create_type grpc_google_default_credentials_create_import; -#define grpc_google_default_credentials_create grpc_google_default_credentials_create_import -typedef void(*grpc_set_ssl_roots_override_callback_type)(grpc_ssl_roots_override_callback cb); -extern grpc_set_ssl_roots_override_callback_type grpc_set_ssl_roots_override_callback_import; -#define grpc_set_ssl_roots_override_callback grpc_set_ssl_roots_override_callback_import -typedef grpc_channel_credentials*(*grpc_ssl_credentials_create_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const verify_peer_options* verify_options, void* reserved); -extern grpc_ssl_credentials_create_type grpc_ssl_credentials_create_import; -#define grpc_ssl_credentials_create grpc_ssl_credentials_create_import -typedef grpc_channel_credentials*(*grpc_ssl_credentials_create_ex_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const grpc_ssl_verify_peer_options* verify_options, void* reserved); -extern grpc_ssl_credentials_create_ex_type grpc_ssl_credentials_create_ex_import; -#define grpc_ssl_credentials_create_ex grpc_ssl_credentials_create_ex_import -typedef grpc_channel_credentials*(*grpc_composite_channel_credentials_create_type)(grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds, void* reserved); -extern grpc_composite_channel_credentials_create_type grpc_composite_channel_credentials_create_import; -#define grpc_composite_channel_credentials_create grpc_composite_channel_credentials_create_import -typedef grpc_call_credentials*(*grpc_composite_call_credentials_create_type)(grpc_call_credentials* creds1, grpc_call_credentials* creds2, void* reserved); -extern grpc_composite_call_credentials_create_type grpc_composite_call_credentials_create_import; -#define grpc_composite_call_credentials_create grpc_composite_call_credentials_create_import -typedef grpc_call_credentials*(*grpc_google_compute_engine_credentials_create_type)(void* reserved); -extern grpc_google_compute_engine_credentials_create_type grpc_google_compute_engine_credentials_create_import; -#define grpc_google_compute_engine_credentials_create grpc_google_compute_engine_credentials_create_import -typedef gpr_timespec(*grpc_max_auth_token_lifetime_type)(void); -extern grpc_max_auth_token_lifetime_type grpc_max_auth_token_lifetime_import; -#define grpc_max_auth_token_lifetime grpc_max_auth_token_lifetime_import -typedef grpc_call_credentials*(*grpc_service_account_jwt_access_credentials_create_type)(const char* json_key, gpr_timespec token_lifetime, void* reserved); -extern grpc_service_account_jwt_access_credentials_create_type grpc_service_account_jwt_access_credentials_create_import; -#define grpc_service_account_jwt_access_credentials_create grpc_service_account_jwt_access_credentials_create_import -typedef grpc_call_credentials*(*grpc_external_account_credentials_create_type)(const char* json_string, const char* scopes_string); -extern grpc_external_account_credentials_create_type grpc_external_account_credentials_create_import; -#define grpc_external_account_credentials_create grpc_external_account_credentials_create_import -typedef grpc_call_credentials*(*grpc_google_refresh_token_credentials_create_type)(const char* json_refresh_token, void* reserved); -extern grpc_google_refresh_token_credentials_create_type grpc_google_refresh_token_credentials_create_import; -#define grpc_google_refresh_token_credentials_create grpc_google_refresh_token_credentials_create_import -typedef grpc_call_credentials*(*grpc_access_token_credentials_create_type)(const char* access_token, void* reserved); -extern grpc_access_token_credentials_create_type grpc_access_token_credentials_create_import; -#define grpc_access_token_credentials_create grpc_access_token_credentials_create_import -typedef grpc_call_credentials*(*grpc_google_iam_credentials_create_type)(const char* authorization_token, const char* authority_selector, void* reserved); -extern grpc_google_iam_credentials_create_type grpc_google_iam_credentials_create_import; -#define grpc_google_iam_credentials_create grpc_google_iam_credentials_create_import -typedef grpc_call_credentials*(*grpc_sts_credentials_create_type)(const grpc_sts_credentials_options* options, void* reserved); -extern grpc_sts_credentials_create_type grpc_sts_credentials_create_import; -#define grpc_sts_credentials_create grpc_sts_credentials_create_import -typedef void(*grpc_auth_metadata_context_copy_type)(grpc_auth_metadata_context* from, grpc_auth_metadata_context* to); -extern grpc_auth_metadata_context_copy_type grpc_auth_metadata_context_copy_import; -#define grpc_auth_metadata_context_copy grpc_auth_metadata_context_copy_import -typedef void(*grpc_auth_metadata_context_reset_type)(grpc_auth_metadata_context* context); -extern grpc_auth_metadata_context_reset_type grpc_auth_metadata_context_reset_import; -#define grpc_auth_metadata_context_reset grpc_auth_metadata_context_reset_import -typedef grpc_call_credentials*(*grpc_metadata_credentials_create_from_plugin_type)(grpc_metadata_credentials_plugin plugin, grpc_security_level min_security_level, void* reserved); -extern grpc_metadata_credentials_create_from_plugin_type grpc_metadata_credentials_create_from_plugin_import; -#define grpc_metadata_credentials_create_from_plugin grpc_metadata_credentials_create_from_plugin_import -typedef grpc_ssl_server_certificate_config*(*grpc_ssl_server_certificate_config_create_type)(const char* pem_root_certs, const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs); -extern grpc_ssl_server_certificate_config_create_type grpc_ssl_server_certificate_config_create_import; -#define grpc_ssl_server_certificate_config_create grpc_ssl_server_certificate_config_create_import -typedef void(*grpc_ssl_server_certificate_config_destroy_type)(grpc_ssl_server_certificate_config* config); -extern grpc_ssl_server_certificate_config_destroy_type grpc_ssl_server_certificate_config_destroy_import; -#define grpc_ssl_server_certificate_config_destroy grpc_ssl_server_certificate_config_destroy_import -typedef grpc_server_credentials*(*grpc_ssl_server_credentials_create_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, int force_client_auth, void* reserved); -extern grpc_ssl_server_credentials_create_type grpc_ssl_server_credentials_create_import; -#define grpc_ssl_server_credentials_create grpc_ssl_server_credentials_create_import -typedef grpc_server_credentials*(*grpc_ssl_server_credentials_create_ex_type)(const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, grpc_ssl_client_certificate_request_type client_certificate_request, void* reserved); -extern grpc_ssl_server_credentials_create_ex_type grpc_ssl_server_credentials_create_ex_import; -#define grpc_ssl_server_credentials_create_ex grpc_ssl_server_credentials_create_ex_import -typedef grpc_ssl_server_credentials_options*(*grpc_ssl_server_credentials_create_options_using_config_type)(grpc_ssl_client_certificate_request_type client_certificate_request, grpc_ssl_server_certificate_config* certificate_config); -extern grpc_ssl_server_credentials_create_options_using_config_type grpc_ssl_server_credentials_create_options_using_config_import; -#define grpc_ssl_server_credentials_create_options_using_config grpc_ssl_server_credentials_create_options_using_config_import -typedef grpc_ssl_server_credentials_options*(*grpc_ssl_server_credentials_create_options_using_config_fetcher_type)(grpc_ssl_client_certificate_request_type client_certificate_request, grpc_ssl_server_certificate_config_callback cb, void* user_data); -extern grpc_ssl_server_credentials_create_options_using_config_fetcher_type grpc_ssl_server_credentials_create_options_using_config_fetcher_import; -#define grpc_ssl_server_credentials_create_options_using_config_fetcher grpc_ssl_server_credentials_create_options_using_config_fetcher_import -typedef void(*grpc_ssl_server_credentials_options_destroy_type)(grpc_ssl_server_credentials_options* options); -extern grpc_ssl_server_credentials_options_destroy_type grpc_ssl_server_credentials_options_destroy_import; -#define grpc_ssl_server_credentials_options_destroy grpc_ssl_server_credentials_options_destroy_import -typedef grpc_server_credentials*(*grpc_ssl_server_credentials_create_with_options_type)(grpc_ssl_server_credentials_options* options); -extern grpc_ssl_server_credentials_create_with_options_type grpc_ssl_server_credentials_create_with_options_import; -#define grpc_ssl_server_credentials_create_with_options grpc_ssl_server_credentials_create_with_options_import -typedef grpc_call_error(*grpc_call_set_credentials_type)(grpc_call* call, grpc_call_credentials* creds); -extern grpc_call_set_credentials_type grpc_call_set_credentials_import; -#define grpc_call_set_credentials grpc_call_set_credentials_import -typedef void(*grpc_server_credentials_set_auth_metadata_processor_type)(grpc_server_credentials* creds, grpc_auth_metadata_processor processor); -extern grpc_server_credentials_set_auth_metadata_processor_type grpc_server_credentials_set_auth_metadata_processor_import; -#define grpc_server_credentials_set_auth_metadata_processor grpc_server_credentials_set_auth_metadata_processor_import -typedef grpc_alts_credentials_options*(*grpc_alts_credentials_client_options_create_type)(void); -extern grpc_alts_credentials_client_options_create_type grpc_alts_credentials_client_options_create_import; -#define grpc_alts_credentials_client_options_create grpc_alts_credentials_client_options_create_import -typedef grpc_alts_credentials_options*(*grpc_alts_credentials_server_options_create_type)(void); -extern grpc_alts_credentials_server_options_create_type grpc_alts_credentials_server_options_create_import; -#define grpc_alts_credentials_server_options_create grpc_alts_credentials_server_options_create_import -typedef void(*grpc_alts_credentials_client_options_add_target_service_account_type)(grpc_alts_credentials_options* options, const char* service_account); -extern grpc_alts_credentials_client_options_add_target_service_account_type grpc_alts_credentials_client_options_add_target_service_account_import; -#define grpc_alts_credentials_client_options_add_target_service_account grpc_alts_credentials_client_options_add_target_service_account_import -typedef void(*grpc_alts_credentials_options_destroy_type)(grpc_alts_credentials_options* options); -extern grpc_alts_credentials_options_destroy_type grpc_alts_credentials_options_destroy_import; -#define grpc_alts_credentials_options_destroy grpc_alts_credentials_options_destroy_import -typedef grpc_channel_credentials*(*grpc_alts_credentials_create_type)(const grpc_alts_credentials_options* options); -extern grpc_alts_credentials_create_type grpc_alts_credentials_create_import; -#define grpc_alts_credentials_create grpc_alts_credentials_create_import -typedef grpc_server_credentials*(*grpc_alts_server_credentials_create_type)(const grpc_alts_credentials_options* options); -extern grpc_alts_server_credentials_create_type grpc_alts_server_credentials_create_import; -#define grpc_alts_server_credentials_create grpc_alts_server_credentials_create_import -typedef grpc_channel_credentials*(*grpc_local_credentials_create_type)(grpc_local_connect_type type); -extern grpc_local_credentials_create_type grpc_local_credentials_create_import; -#define grpc_local_credentials_create grpc_local_credentials_create_import -typedef grpc_server_credentials*(*grpc_local_server_credentials_create_type)(grpc_local_connect_type type); -extern grpc_local_server_credentials_create_type grpc_local_server_credentials_create_import; -#define grpc_local_server_credentials_create grpc_local_server_credentials_create_import -typedef grpc_tls_identity_pairs*(*grpc_tls_identity_pairs_create_type)(); -extern grpc_tls_identity_pairs_create_type grpc_tls_identity_pairs_create_import; -#define grpc_tls_identity_pairs_create grpc_tls_identity_pairs_create_import -typedef void(*grpc_tls_identity_pairs_add_pair_type)(grpc_tls_identity_pairs* pairs, const char* private_key, const char* cert_chain); -extern grpc_tls_identity_pairs_add_pair_type grpc_tls_identity_pairs_add_pair_import; -#define grpc_tls_identity_pairs_add_pair grpc_tls_identity_pairs_add_pair_import -typedef void(*grpc_tls_identity_pairs_destroy_type)(grpc_tls_identity_pairs* pairs); -extern grpc_tls_identity_pairs_destroy_type grpc_tls_identity_pairs_destroy_import; -#define grpc_tls_identity_pairs_destroy grpc_tls_identity_pairs_destroy_import -typedef grpc_tls_certificate_provider*(*grpc_tls_certificate_provider_static_data_create_type)(const char* root_certificate, grpc_tls_identity_pairs* pem_key_cert_pairs); -extern grpc_tls_certificate_provider_static_data_create_type grpc_tls_certificate_provider_static_data_create_import; -#define grpc_tls_certificate_provider_static_data_create grpc_tls_certificate_provider_static_data_create_import -typedef grpc_tls_certificate_provider*(*grpc_tls_certificate_provider_file_watcher_create_type)(const char* private_key_path, const char* identity_certificate_path, const char* root_cert_path, unsigned int refresh_interval_sec); -extern grpc_tls_certificate_provider_file_watcher_create_type grpc_tls_certificate_provider_file_watcher_create_import; -#define grpc_tls_certificate_provider_file_watcher_create grpc_tls_certificate_provider_file_watcher_create_import -typedef void(*grpc_tls_certificate_provider_release_type)(grpc_tls_certificate_provider* provider); -extern grpc_tls_certificate_provider_release_type grpc_tls_certificate_provider_release_import; -#define grpc_tls_certificate_provider_release grpc_tls_certificate_provider_release_import -typedef grpc_tls_credentials_options*(*grpc_tls_credentials_options_create_type)(void); -extern grpc_tls_credentials_options_create_type grpc_tls_credentials_options_create_import; -#define grpc_tls_credentials_options_create grpc_tls_credentials_options_create_import -typedef void(*grpc_tls_credentials_options_set_min_tls_version_type)(grpc_tls_credentials_options* options, grpc_tls_version min_tls_version); -extern grpc_tls_credentials_options_set_min_tls_version_type grpc_tls_credentials_options_set_min_tls_version_import; -#define grpc_tls_credentials_options_set_min_tls_version grpc_tls_credentials_options_set_min_tls_version_import -typedef void(*grpc_tls_credentials_options_set_max_tls_version_type)(grpc_tls_credentials_options* options, grpc_tls_version max_tls_version); -extern grpc_tls_credentials_options_set_max_tls_version_type grpc_tls_credentials_options_set_max_tls_version_import; -#define grpc_tls_credentials_options_set_max_tls_version grpc_tls_credentials_options_set_max_tls_version_import -typedef grpc_tls_credentials_options*(*grpc_tls_credentials_options_copy_type)(grpc_tls_credentials_options* options); -extern grpc_tls_credentials_options_copy_type grpc_tls_credentials_options_copy_import; -#define grpc_tls_credentials_options_copy grpc_tls_credentials_options_copy_import -typedef void(*grpc_tls_credentials_options_destroy_type)(grpc_tls_credentials_options* options); -extern grpc_tls_credentials_options_destroy_type grpc_tls_credentials_options_destroy_import; -#define grpc_tls_credentials_options_destroy grpc_tls_credentials_options_destroy_import -typedef void(*grpc_tls_credentials_options_set_certificate_provider_type)(grpc_tls_credentials_options* options, grpc_tls_certificate_provider* provider); -extern grpc_tls_credentials_options_set_certificate_provider_type grpc_tls_credentials_options_set_certificate_provider_import; -#define grpc_tls_credentials_options_set_certificate_provider grpc_tls_credentials_options_set_certificate_provider_import -typedef void(*grpc_tls_credentials_options_watch_root_certs_type)(grpc_tls_credentials_options* options); -extern grpc_tls_credentials_options_watch_root_certs_type grpc_tls_credentials_options_watch_root_certs_import; -#define grpc_tls_credentials_options_watch_root_certs grpc_tls_credentials_options_watch_root_certs_import -typedef void(*grpc_tls_credentials_options_set_root_cert_name_type)(grpc_tls_credentials_options* options, const char* root_cert_name); -extern grpc_tls_credentials_options_set_root_cert_name_type grpc_tls_credentials_options_set_root_cert_name_import; -#define grpc_tls_credentials_options_set_root_cert_name grpc_tls_credentials_options_set_root_cert_name_import -typedef void(*grpc_tls_credentials_options_watch_identity_key_cert_pairs_type)(grpc_tls_credentials_options* options); -extern grpc_tls_credentials_options_watch_identity_key_cert_pairs_type grpc_tls_credentials_options_watch_identity_key_cert_pairs_import; -#define grpc_tls_credentials_options_watch_identity_key_cert_pairs grpc_tls_credentials_options_watch_identity_key_cert_pairs_import -typedef void(*grpc_tls_credentials_options_set_identity_cert_name_type)(grpc_tls_credentials_options* options, const char* identity_cert_name); -extern grpc_tls_credentials_options_set_identity_cert_name_type grpc_tls_credentials_options_set_identity_cert_name_import; -#define grpc_tls_credentials_options_set_identity_cert_name grpc_tls_credentials_options_set_identity_cert_name_import -typedef void(*grpc_tls_credentials_options_set_cert_request_type_type)(grpc_tls_credentials_options* options, grpc_ssl_client_certificate_request_type type); -extern grpc_tls_credentials_options_set_cert_request_type_type grpc_tls_credentials_options_set_cert_request_type_import; -#define grpc_tls_credentials_options_set_cert_request_type grpc_tls_credentials_options_set_cert_request_type_import -typedef void(*grpc_tls_credentials_options_set_crl_directory_type)(grpc_tls_credentials_options* options, const char* crl_directory); -extern grpc_tls_credentials_options_set_crl_directory_type grpc_tls_credentials_options_set_crl_directory_import; -#define grpc_tls_credentials_options_set_crl_directory grpc_tls_credentials_options_set_crl_directory_import -typedef void(*grpc_tls_credentials_options_set_verify_server_cert_type)(grpc_tls_credentials_options* options, int verify_server_cert); -extern grpc_tls_credentials_options_set_verify_server_cert_type grpc_tls_credentials_options_set_verify_server_cert_import; -#define grpc_tls_credentials_options_set_verify_server_cert grpc_tls_credentials_options_set_verify_server_cert_import -typedef void(*grpc_tls_credentials_options_set_send_client_ca_list_type)(grpc_tls_credentials_options* options, bool send_client_ca_list); -extern grpc_tls_credentials_options_set_send_client_ca_list_type grpc_tls_credentials_options_set_send_client_ca_list_import; -#define grpc_tls_credentials_options_set_send_client_ca_list grpc_tls_credentials_options_set_send_client_ca_list_import -typedef void(*grpc_tls_credentials_options_set_check_call_host_type)(grpc_tls_credentials_options* options, int check_call_host); -extern grpc_tls_credentials_options_set_check_call_host_type grpc_tls_credentials_options_set_check_call_host_import; -#define grpc_tls_credentials_options_set_check_call_host grpc_tls_credentials_options_set_check_call_host_import -typedef grpc_channel_credentials*(*grpc_insecure_credentials_create_type)(); -extern grpc_insecure_credentials_create_type grpc_insecure_credentials_create_import; -#define grpc_insecure_credentials_create grpc_insecure_credentials_create_import -typedef grpc_server_credentials*(*grpc_insecure_server_credentials_create_type)(); -extern grpc_insecure_server_credentials_create_type grpc_insecure_server_credentials_create_import; -#define grpc_insecure_server_credentials_create grpc_insecure_server_credentials_create_import -typedef grpc_channel_credentials*(*grpc_xds_credentials_create_type)(grpc_channel_credentials* fallback_credentials); -extern grpc_xds_credentials_create_type grpc_xds_credentials_create_import; -#define grpc_xds_credentials_create grpc_xds_credentials_create_import -typedef grpc_server_credentials*(*grpc_xds_server_credentials_create_type)(grpc_server_credentials* fallback_credentials); -extern grpc_xds_server_credentials_create_type grpc_xds_server_credentials_create_import; -#define grpc_xds_server_credentials_create grpc_xds_server_credentials_create_import typedef grpc_authorization_policy_provider*(*grpc_authorization_policy_provider_static_data_create_type)(const char* authz_policy, grpc_status_code* code, const char** error_details); extern grpc_authorization_policy_provider_static_data_create_type grpc_authorization_policy_provider_static_data_create_import; #define grpc_authorization_policy_provider_static_data_create grpc_authorization_policy_provider_static_data_create_import @@ -575,9 +579,6 @@ extern grpc_authorization_policy_provider_file_watcher_create_type grpc_authoriz typedef void(*grpc_authorization_policy_provider_release_type)(grpc_authorization_policy_provider* provider); extern grpc_authorization_policy_provider_release_type grpc_authorization_policy_provider_release_import; #define grpc_authorization_policy_provider_release grpc_authorization_policy_provider_release_import -typedef void(*grpc_tls_credentials_options_set_tls_session_key_log_file_path_type)(grpc_tls_credentials_options* options, const char* path); -extern grpc_tls_credentials_options_set_tls_session_key_log_file_path_type grpc_tls_credentials_options_set_tls_session_key_log_file_path_import; -#define grpc_tls_credentials_options_set_tls_session_key_log_file_path grpc_tls_credentials_options_set_tls_session_key_log_file_path_import typedef grpc_slice(*grpc_slice_ref_type)(grpc_slice s); extern grpc_slice_ref_type grpc_slice_ref_import; #define grpc_slice_ref grpc_slice_ref_import diff --git a/src/ruby/ext/grpc/rb_server.c b/src/ruby/ext/grpc/rb_server.c index 387dcff2d27..51ba4a91eb2 100644 --- a/src/ruby/ext/grpc/rb_server.c +++ b/src/ruby/ext/grpc/rb_server.c @@ -29,6 +29,7 @@ #include "rb_server_credentials.h" #include "rb_xds_server_credentials.h" +#include #include #include #include diff --git a/src/ruby/ext/grpc/rb_server_credentials.c b/src/ruby/ext/grpc/rb_server_credentials.c index 42c259015cd..73c754d5352 100644 --- a/src/ruby/ext/grpc/rb_server_credentials.c +++ b/src/ruby/ext/grpc/rb_server_credentials.c @@ -23,6 +23,7 @@ #include "rb_grpc.h" #include "rb_grpc_imports.generated.h" +#include #include #include #include diff --git a/src/ruby/ext/grpc/rb_server_credentials.h b/src/ruby/ext/grpc/rb_server_credentials.h index bb14b575c05..64b22715d99 100644 --- a/src/ruby/ext/grpc/rb_server_credentials.h +++ b/src/ruby/ext/grpc/rb_server_credentials.h @@ -23,6 +23,7 @@ #include +#include #include /* Initializes the ruby ServerCredentials class. */ diff --git a/src/ruby/ext/grpc/rb_xds_channel_credentials.c b/src/ruby/ext/grpc/rb_xds_channel_credentials.c index db3d6dbdac4..56b08d99287 100644 --- a/src/ruby/ext/grpc/rb_xds_channel_credentials.c +++ b/src/ruby/ext/grpc/rb_xds_channel_credentials.c @@ -27,6 +27,7 @@ #include "rb_grpc.h" #include "rb_grpc_imports.generated.h" +#include #include #include #include diff --git a/src/ruby/ext/grpc/rb_xds_server_credentials.c b/src/ruby/ext/grpc/rb_xds_server_credentials.c index 3d4ec5afe53..8186d0eb49e 100644 --- a/src/ruby/ext/grpc/rb_xds_server_credentials.c +++ b/src/ruby/ext/grpc/rb_xds_server_credentials.c @@ -24,6 +24,7 @@ #include "rb_grpc_imports.generated.h" #include "rb_server_credentials.h" +#include #include #include #include diff --git a/src/ruby/ext/grpc/rb_xds_server_credentials.h b/src/ruby/ext/grpc/rb_xds_server_credentials.h index eff00c7dcf5..3ec1ced8e4b 100644 --- a/src/ruby/ext/grpc/rb_xds_server_credentials.h +++ b/src/ruby/ext/grpc/rb_xds_server_credentials.h @@ -23,6 +23,7 @@ #include +#include #include /* Initializes the ruby XdsServerCredentials class. */ diff --git a/test/core/bad_client/bad_client.cc b/test/core/bad_client/bad_client.cc index f0997e4b13d..7394e109b5e 100644 --- a/test/core/bad_client/bad_client.cc +++ b/test/core/bad_client/bad_client.cc @@ -21,6 +21,8 @@ #include #include +#include "absl/log/check.h" + #include #include #include @@ -76,7 +78,7 @@ static void server_setup_transport(void* ts, grpc_core::Transport* transport) { thd_args* a = static_cast(ts); grpc_core::ExecCtx exec_ctx; grpc_core::Server* core_server = grpc_core::Server::FromC(a->server); - GPR_ASSERT(GRPC_LOG_IF_ERROR( + CHECK(GRPC_LOG_IF_ERROR( "SetupTransport", core_server->SetupTransport(transport, /*accepting_pollset=*/nullptr, core_server->channel_args(), @@ -135,8 +137,7 @@ void grpc_run_client_side_validator(grpc_bad_client_arg* arg, uint32_t flags, // Await completion, unless the request is large and write may not finish // before the peer shuts down. if (!(flags & GRPC_BAD_CLIENT_LARGE_REQUEST)) { - GPR_ASSERT( - gpr_event_wait(&done_write, grpc_timeout_seconds_to_deadline(5))); + CHECK(gpr_event_wait(&done_write, grpc_timeout_seconds_to_deadline(5))); } if (flags & GRPC_BAD_CLIENT_DISCONNECT) { @@ -161,13 +162,13 @@ void grpc_run_client_side_validator(grpc_bad_client_arg* arg, uint32_t flags, /*urgent=*/true, /*min_progress_size=*/1); grpc_core::ExecCtx::Get()->Flush(); do { - GPR_ASSERT(gpr_time_cmp(deadline, gpr_now(deadline.clock_type)) > 0); + CHECK_GT(gpr_time_cmp(deadline, gpr_now(deadline.clock_type)), 0); // Perform a cq next just to provide a thread that can read incoming // bytes on the client fd - GPR_ASSERT(grpc_completion_queue_next( - client_cq, grpc_timeout_milliseconds_to_deadline(100), - nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + client_cq, grpc_timeout_milliseconds_to_deadline(100), + nullptr) + .type == GRPC_QUEUE_TIMEOUT); } while (!gpr_event_get(&read_done_event)); if (arg->client_validator(&incoming, arg->client_validator_arg)) break; gpr_log(GPR_INFO, @@ -187,10 +188,9 @@ void grpc_run_client_side_validator(grpc_bad_client_arg* arg, uint32_t flags, // Make sure that the client is done writing while (!gpr_event_get(&done_write)) { - GPR_ASSERT( - grpc_completion_queue_next( - client_cq, grpc_timeout_milliseconds_to_deadline(100), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + client_cq, grpc_timeout_milliseconds_to_deadline(100), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } grpc_slice_buffer_destroy(&outgoing); @@ -238,7 +238,7 @@ void grpc_run_bad_client_test( grpc_endpoint_add_to_pollset(sfd.server, grpc_cq_pollset(a.cq)); // Check a ground truth - GPR_ASSERT(grpc_core::Server::FromC(a.server)->HasOpenConnections()); + CHECK(grpc_core::Server::FromC(a.server)->HasOpenConnections()); gpr_event_init(&a.done_thd); a.validator = server_validator; @@ -251,17 +251,16 @@ void grpc_run_bad_client_test( &sfd, client_cq); } // Wait for server thread to finish - GPR_ASSERT(gpr_event_wait(&a.done_thd, grpc_timeout_seconds_to_deadline(5))); + CHECK(gpr_event_wait(&a.done_thd, grpc_timeout_seconds_to_deadline(5))); // Shutdown. shutdown_client(&sfd.client); server_validator_thd.Join(); shutdown_cq = grpc_completion_queue_create_for_pluck(nullptr); grpc_server_shutdown_and_notify(a.server, shutdown_cq, nullptr); - GPR_ASSERT(grpc_completion_queue_pluck(shutdown_cq, nullptr, - grpc_timeout_seconds_to_deadline(1), - nullptr) - .type == GRPC_OP_COMPLETE); + CHECK(grpc_completion_queue_pluck( + shutdown_cq, nullptr, grpc_timeout_seconds_to_deadline(1), nullptr) + .type == GRPC_OP_COMPLETE); grpc_completion_queue_destroy(shutdown_cq); grpc_server_destroy(a.server); grpc_completion_queue_destroy(a.cq); @@ -301,7 +300,7 @@ bool rst_stream_client_validator(grpc_slice_buffer* incoming, void* /*arg*/) { grpc_slice_buffer_init(&last_frame_buffer); grpc_slice_buffer_trim_end(incoming, kExpectedFrameLength, &last_frame_buffer); - GPR_ASSERT(last_frame_buffer.count == 1); + CHECK_EQ(last_frame_buffer.count, 1u); grpc_slice last_frame = last_frame_buffer.slices[0]; const uint8_t* p = GRPC_SLICE_START_PTR(last_frame); @@ -340,12 +339,12 @@ void server_verifier_request_call(grpc_server* server, error = grpc_server_request_call(server, &s, &call_details, &request_metadata_recv, cq, cq, grpc_core::CqVerifier::tag(101)); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(101), true); cqv.Verify(); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.host, "localhost")); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo/bar")); + CHECK_EQ(grpc_slice_str_cmp(call_details.host, "localhost"), 0); + CHECK_EQ(grpc_slice_str_cmp(call_details.method, "/foo/bar"), 0); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); diff --git a/test/core/bad_client/generate_tests.bzl b/test/core/bad_client/generate_tests.bzl index 48949315472..4eb204175ec 100755 --- a/test/core/bad_client/generate_tests.bzl +++ b/test/core/bad_client/generate_tests.bzl @@ -51,6 +51,9 @@ def grpc_bad_client_tests(): "//test/core/end2end:cq_verifier", "//:grpc_http_filters", ], + external_deps = [ + "absl/log:check", + ], ) for t, topt in BAD_CLIENT_TESTS.items(): grpc_cc_test( @@ -59,6 +62,7 @@ def grpc_bad_client_tests(): deps = [":bad_client_test"], tags = ["bad_client_test"], external_deps = [ + "absl/log:check", "gtest", ], ) diff --git a/test/core/bad_client/tests/bad_streaming_id.cc b/test/core/bad_client/tests/bad_streaming_id.cc index 14c676fb0d9..2715f52e8f7 100644 --- a/test/core/bad_client/tests/bad_streaming_id.cc +++ b/test/core/bad_client/tests/bad_streaming_id.cc @@ -20,6 +20,8 @@ #include +#include "absl/log/check.h" + #include #include @@ -80,9 +82,9 @@ namespace { void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/badreq.cc b/test/core/bad_client/tests/badreq.cc index 856e8851287..9b6b5ea7339 100644 --- a/test/core/bad_client/tests/badreq.cc +++ b/test/core/bad_client/tests/badreq.cc @@ -16,6 +16,8 @@ // // +#include "absl/log/check.h" + #include #include @@ -30,9 +32,9 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/connection_prefix.cc b/test/core/bad_client/tests/connection_prefix.cc index 83b513b511c..604e7040f12 100644 --- a/test/core/bad_client/tests/connection_prefix.cc +++ b/test/core/bad_client/tests/connection_prefix.cc @@ -16,6 +16,8 @@ // // +#include "absl/log/check.h" + #include #include @@ -26,9 +28,9 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/duplicate_header.cc b/test/core/bad_client/tests/duplicate_header.cc index ad5754d1db9..c4edc871355 100644 --- a/test/core/bad_client/tests/duplicate_header.cc +++ b/test/core/bad_client/tests/duplicate_header.cc @@ -18,6 +18,8 @@ #include +#include "absl/log/check.h" + #include #include #include @@ -70,7 +72,7 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, error = grpc_server_request_call(server, &s, &call_details, &request_metadata_recv, cq, cq, grpc_core::CqVerifier::tag(101)); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); bool got = false; cqv.Expect(grpc_core::CqVerifier::tag(101), grpc_core::CqVerifier::Maybe{&got}); @@ -84,8 +86,8 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, return; } - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.host, "localhost")); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo/bar")); + CHECK_EQ(grpc_slice_str_cmp(call_details.host, "localhost"), 0); + CHECK_EQ(grpc_slice_str_cmp(call_details.method, "/foo/bar"), 0); memset(ops, 0, sizeof(ops)); op = ops; @@ -101,7 +103,7 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, op++; error = grpc_call_start_batch(s, ops, static_cast(op - ops), grpc_core::CqVerifier::tag(102), nullptr); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(102), grpc_core::CqVerifier::AnyStatus()); @@ -124,7 +126,7 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, op++; error = grpc_call_start_batch(s, ops, static_cast(op - ops), grpc_core::CqVerifier::tag(103), nullptr); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(103), true); cqv.Verify(); diff --git a/test/core/bad_client/tests/head_of_line_blocking.cc b/test/core/bad_client/tests/head_of_line_blocking.cc index 7360d8e7e7a..07122148202 100644 --- a/test/core/bad_client/tests/head_of_line_blocking.cc +++ b/test/core/bad_client/tests/head_of_line_blocking.cc @@ -21,6 +21,8 @@ #include +#include "absl/log/check.h" + #include #include #include @@ -85,11 +87,11 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, error = grpc_server_request_registered_call( server, registered_method, &s, &deadline, &request_metadata_recv, &payload, cq, cq, grpc_core::CqVerifier::tag(101)); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(101), true); cqv.Verify(); - GPR_ASSERT(payload != nullptr); + CHECK_NE(payload, nullptr); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_unref(s); diff --git a/test/core/bad_client/tests/headers.cc b/test/core/bad_client/tests/headers.cc index f1b4b14251e..dca232d2afa 100644 --- a/test/core/bad_client/tests/headers.cc +++ b/test/core/bad_client/tests/headers.cc @@ -16,8 +16,9 @@ // // +#include "absl/log/check.h" + #include -#include #include "src/core/lib/surface/server.h" #include "test/core/bad_client/bad_client.h" @@ -30,9 +31,9 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/initial_settings_frame.cc b/test/core/bad_client/tests/initial_settings_frame.cc index 384d1662ab2..8b992b0b220 100644 --- a/test/core/bad_client/tests/initial_settings_frame.cc +++ b/test/core/bad_client/tests/initial_settings_frame.cc @@ -16,11 +16,11 @@ // // +#include "absl/log/check.h" #include "absl/strings/str_cat.h" #include #include -#include #include "src/core/lib/experiments/experiments.h" #include "src/core/lib/surface/server.h" @@ -87,9 +87,9 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } @@ -109,13 +109,14 @@ static void single_request_verifier(grpc_server* server, error = grpc_server_request_call(server, &s, &call_details, &request_metadata_recv, cq, cq, grpc_core::CqVerifier::tag(101)); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(101), true); cqv.Verify(); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.host, "localhost")); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, - absl::StrCat("/foo/bar", i).c_str())); + CHECK_EQ(grpc_slice_str_cmp(call_details.host, "localhost"), 0); + CHECK_EQ(grpc_slice_str_cmp(call_details.method, + absl::StrCat("/foo/bar", i).c_str()), + 0); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); diff --git a/test/core/bad_client/tests/out_of_bounds.cc b/test/core/bad_client/tests/out_of_bounds.cc index 00eda5db9b8..e23ec13df21 100644 --- a/test/core/bad_client/tests/out_of_bounds.cc +++ b/test/core/bad_client/tests/out_of_bounds.cc @@ -20,6 +20,8 @@ #include +#include "absl/log/check.h" + #include #include @@ -35,9 +37,9 @@ namespace { void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/server_registered_method.cc b/test/core/bad_client/tests/server_registered_method.cc index 2b9059bda19..67a67b744e8 100644 --- a/test/core/bad_client/tests/server_registered_method.cc +++ b/test/core/bad_client/tests/server_registered_method.cc @@ -16,6 +16,8 @@ // // +#include "absl/log/check.h" + #include #include #include @@ -55,11 +57,11 @@ static void verifier_succeeds(grpc_server* server, grpc_completion_queue* cq, error = grpc_server_request_registered_call( server, registered_method, &s, &deadline, &request_metadata_recv, &payload, cq, cq, grpc_core::CqVerifier::tag(101)); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(101), true); cqv.Verify(); - GPR_ASSERT(payload != nullptr); + CHECK_NE(payload, nullptr); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_unref(s); @@ -69,9 +71,9 @@ static void verifier_succeeds(grpc_server* server, grpc_completion_queue* cq, static void verifier_fails(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/simple_request.cc b/test/core/bad_client/tests/simple_request.cc index dcc650194fe..d3c90ed81d6 100644 --- a/test/core/bad_client/tests/simple_request.cc +++ b/test/core/bad_client/tests/simple_request.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "absl/log/check.h" + #include #include #include @@ -116,12 +118,12 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, error = grpc_server_request_call(server, &s, &call_details, &request_metadata_recv, cq, cq, grpc_core::CqVerifier::tag(101)); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(101), true); cqv.Verify(); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.host, "localhost")); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo/bar")); + CHECK_EQ(grpc_slice_str_cmp(call_details.host, "localhost"), 0); + CHECK_EQ(grpc_slice_str_cmp(call_details.method, "/foo/bar"), 0); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); @@ -144,12 +146,12 @@ static void VerifyRpcDoesNotGetCanceled(grpc_server* server, error = grpc_server_request_call(server, &s, &call_details, &request_metadata_recv, cq, cq, grpc_core::CqVerifier::tag(101)); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(101), true); cqv.Verify(); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.host, "localhost")); - GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo/bar")); + CHECK_EQ(grpc_slice_str_cmp(call_details.host, "localhost"), 0); + CHECK_EQ(grpc_slice_str_cmp(call_details.method, "/foo/bar"), 0); grpc_op* op; grpc_op ops[6]; @@ -176,13 +178,13 @@ static void VerifyRpcDoesNotGetCanceled(grpc_server* server, op++; error = grpc_call_start_batch(s, ops, static_cast(op - ops), grpc_core::CqVerifier::tag(103), nullptr); - GPR_ASSERT(GRPC_CALL_OK == error); + CHECK_EQ(error, GRPC_CALL_OK); cqv.Expect(grpc_core::CqVerifier::tag(103), true); cqv.Verify(); // If the call had an error, `was_cancelled` would be 1. - // GPR_ASSERT(was_cancelled == 1); + // CHECK_EQ(was_cancelled, 1); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); @@ -192,9 +194,9 @@ static void VerifyRpcDoesNotGetCanceled(grpc_server* server, static void failure_verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/unknown_frame.cc b/test/core/bad_client/tests/unknown_frame.cc index 6fa368870fc..8eb847bd119 100644 --- a/test/core/bad_client/tests/unknown_frame.cc +++ b/test/core/bad_client/tests/unknown_frame.cc @@ -20,6 +20,8 @@ #include +#include "absl/log/check.h" + #include #include @@ -30,9 +32,9 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_client/tests/window_overflow.cc b/test/core/bad_client/tests/window_overflow.cc index 401d1bbce71..f16645a0789 100644 --- a/test/core/bad_client/tests/window_overflow.cc +++ b/test/core/bad_client/tests/window_overflow.cc @@ -17,6 +17,8 @@ #include +#include "absl/log/check.h" + #include #include #include @@ -45,9 +47,9 @@ static void verifier(grpc_server* server, grpc_completion_queue* cq, void* /*registered_method*/) { while (grpc_core::Server::FromC(server)->HasOpenConnections()) { - GPR_ASSERT(grpc_completion_queue_next( - cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) - .type == GRPC_QUEUE_TIMEOUT); + CHECK(grpc_completion_queue_next( + cq, grpc_timeout_milliseconds_to_deadline(20), nullptr) + .type == GRPC_QUEUE_TIMEOUT); } } diff --git a/test/core/bad_ssl/bad_ssl_test.cc b/test/core/bad_ssl/bad_ssl_test.cc index 5faa7b7bc5a..40b1d87c66b 100644 --- a/test/core/bad_ssl/bad_ssl_test.cc +++ b/test/core/bad_ssl/bad_ssl_test.cc @@ -21,6 +21,7 @@ #include +#include #include #include #include diff --git a/test/core/bad_ssl/servers/alpn.cc b/test/core/bad_ssl/servers/alpn.cc index 14693494cee..049e87f9700 100644 --- a/test/core/bad_ssl/servers/alpn.cc +++ b/test/core/bad_ssl/servers/alpn.cc @@ -20,6 +20,7 @@ #include +#include #include #include #include diff --git a/test/core/bad_ssl/servers/cert.cc b/test/core/bad_ssl/servers/cert.cc index 954c28fca7f..4c6b26a025c 100644 --- a/test/core/bad_ssl/servers/cert.cc +++ b/test/core/bad_ssl/servers/cert.cc @@ -16,6 +16,7 @@ // // +#include #include #include #include diff --git a/test/core/channel/channel_args_test.cc b/test/core/channel/channel_args_test.cc index fd035ccc12d..9e722c67f84 100644 --- a/test/core/channel/channel_args_test.cc +++ b/test/core/channel/channel_args_test.cc @@ -22,6 +22,7 @@ #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/channel/channel_trace_test.cc b/test/core/channel/channel_trace_test.cc index 1a346f3da6c..2396c4a3945 100644 --- a/test/core/channel/channel_trace_test.cc +++ b/test/core/channel/channel_trace_test.cc @@ -24,6 +24,7 @@ #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/channel/channelz_test.cc b/test/core/channel/channelz_test.cc index 3b57b4a6ef7..973af3690eb 100644 --- a/test/core/channel/channelz_test.cc +++ b/test/core/channel/channelz_test.cc @@ -30,6 +30,7 @@ #include "absl/status/statusor.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/end2end/bad_server_response_test.cc b/test/core/end2end/bad_server_response_test.cc index ea613b36fbd..b898c0aa23d 100644 --- a/test/core/end2end/bad_server_response_test.cc +++ b/test/core/end2end/bad_server_response_test.cc @@ -24,6 +24,7 @@ #include #include +#include #include #include #include diff --git a/test/core/end2end/connection_refused_test.cc b/test/core/end2end/connection_refused_test.cc index a670f4ece5d..b3deb41f14f 100644 --- a/test/core/end2end/connection_refused_test.cc +++ b/test/core/end2end/connection_refused_test.cc @@ -20,6 +20,7 @@ #include +#include #include #include #include diff --git a/test/core/end2end/dualstack_socket_test.cc b/test/core/end2end/dualstack_socket_test.cc index db0d1d710a6..4c4c782e3b2 100644 --- a/test/core/end2end/dualstack_socket_test.cc +++ b/test/core/end2end/dualstack_socket_test.cc @@ -42,6 +42,7 @@ #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/test/core/end2end/end2end_test_suites.cc b/test/core/end2end/end2end_test_suites.cc index 625d1a8190a..f1f86668b20 100644 --- a/test/core/end2end/end2end_test_suites.cc +++ b/test/core/end2end/end2end_test_suites.cc @@ -34,6 +34,7 @@ #include "gtest/gtest.h" #include +#include #include #include #include diff --git a/test/core/end2end/end2end_tests.h b/test/core/end2end/end2end_tests.h index 410f3366014..f033f608061 100644 --- a/test/core/end2end/end2end_tests.h +++ b/test/core/end2end/end2end_tests.h @@ -42,6 +42,7 @@ #include #include +#include #include #include #include diff --git a/test/core/end2end/fixtures/h2_oauth2_common.h b/test/core/end2end/fixtures/h2_oauth2_common.h index 57ae5a7d60d..e66f341059a 100644 --- a/test/core/end2end/fixtures/h2_oauth2_common.h +++ b/test/core/end2end/fixtures/h2_oauth2_common.h @@ -17,6 +17,7 @@ #include +#include #include #include #include diff --git a/test/core/end2end/fixtures/h2_ssl_cred_reload_fixture.h b/test/core/end2end/fixtures/h2_ssl_cred_reload_fixture.h index fe6bc5d43dd..5b49fcb39e5 100644 --- a/test/core/end2end/fixtures/h2_ssl_cred_reload_fixture.h +++ b/test/core/end2end/fixtures/h2_ssl_cred_reload_fixture.h @@ -17,6 +17,7 @@ #include +#include #include #include #include diff --git a/test/core/end2end/fixtures/h2_ssl_tls_common.h b/test/core/end2end/fixtures/h2_ssl_tls_common.h index 1a2d8da331d..e026ccbd381 100644 --- a/test/core/end2end/fixtures/h2_ssl_tls_common.h +++ b/test/core/end2end/fixtures/h2_ssl_tls_common.h @@ -17,6 +17,7 @@ #include +#include #include #include #include diff --git a/test/core/end2end/fixtures/h2_tls_common.h b/test/core/end2end/fixtures/h2_tls_common.h index 5fd2972fd0f..0abc56e6d06 100644 --- a/test/core/end2end/fixtures/h2_tls_common.h +++ b/test/core/end2end/fixtures/h2_tls_common.h @@ -26,6 +26,7 @@ #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/test/core/end2end/fixtures/local_util.cc b/test/core/end2end/fixtures/local_util.cc index 7cb814de9e2..2c4059b1973 100644 --- a/test/core/end2end/fixtures/local_util.cc +++ b/test/core/end2end/fixtures/local_util.cc @@ -22,6 +22,7 @@ #include +#include #include #include #include diff --git a/test/core/end2end/fixtures/secure_fixture.h b/test/core/end2end/fixtures/secure_fixture.h index d047e712d21..8a64b49fc75 100644 --- a/test/core/end2end/fixtures/secure_fixture.h +++ b/test/core/end2end/fixtures/secure_fixture.h @@ -20,6 +20,7 @@ #include "absl/functional/any_invocable.h" +#include #include #include #include diff --git a/test/core/end2end/fuzzers/api_fuzzer.cc b/test/core/end2end/fuzzers/api_fuzzer.cc index 98dd58e7df5..213c13b427a 100644 --- a/test/core/end2end/fuzzers/api_fuzzer.cc +++ b/test/core/end2end/fuzzers/api_fuzzer.cc @@ -32,8 +32,11 @@ #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" +#include "absl/time/clock.h" +#include "absl/time/time.h" #include "absl/types/optional.h" +#include #include #include #include @@ -157,9 +160,18 @@ class FuzzerDNSResolver : public grpc_core::DNSResolver { } absl::StatusOr> LookupHostnameBlocking( - absl::string_view /* name */, - absl::string_view /* default_port */) override { - GPR_ASSERT(0); + absl::string_view name, absl::string_view default_port) override { + // To mimic the resolution delay + absl::SleepFor(absl::Seconds(1)); + if (name == "server") { + std::vector addrs; + grpc_resolved_address addr; + memset(&addr, 0, sizeof(addr)); + addrs.push_back(addr); + return addrs; + } else { + return absl::UnknownError("Resolution failed"); + } } TaskHandle LookupSRV( diff --git a/test/core/end2end/fuzzers/server_fuzzer_chttp2.cc b/test/core/end2end/fuzzers/server_fuzzer_chttp2.cc index b01b357825e..f95e2c69e2b 100644 --- a/test/core/end2end/fuzzers/server_fuzzer_chttp2.cc +++ b/test/core/end2end/fuzzers/server_fuzzer_chttp2.cc @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include #include #include "src/libfuzzer/libfuzzer_macro.h" diff --git a/test/core/end2end/goaway_server_test.cc b/test/core/end2end/goaway_server_test.cc index 0359b71db11..c8e958edc30 100644 --- a/test/core/end2end/goaway_server_test.cc +++ b/test/core/end2end/goaway_server_test.cc @@ -31,6 +31,7 @@ #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" +#include #include #include #include diff --git a/test/core/end2end/h2_ssl_cert_test.cc b/test/core/end2end/h2_ssl_cert_test.cc index 584bceb7ef6..d1d94e5ac3a 100644 --- a/test/core/end2end/h2_ssl_cert_test.cc +++ b/test/core/end2end/h2_ssl_cert_test.cc @@ -27,6 +27,7 @@ #include "absl/types/optional.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/end2end/h2_ssl_session_reuse_test.cc b/test/core/end2end/h2_ssl_session_reuse_test.cc index 875b9f79e53..55243de78ed 100644 --- a/test/core/end2end/h2_ssl_session_reuse_test.cc +++ b/test/core/end2end/h2_ssl_session_reuse_test.cc @@ -24,6 +24,7 @@ #include "absl/types/optional.h" +#include #include #include #include diff --git a/test/core/end2end/h2_tls_peer_property_external_verifier_test.cc b/test/core/end2end/h2_tls_peer_property_external_verifier_test.cc index 8cc76b5bfe1..958ae061e67 100644 --- a/test/core/end2end/h2_tls_peer_property_external_verifier_test.cc +++ b/test/core/end2end/h2_tls_peer_property_external_verifier_test.cc @@ -24,6 +24,7 @@ #include "absl/types/optional.h" +#include #include #include #include diff --git a/test/core/end2end/invalid_call_argument_test.cc b/test/core/end2end/invalid_call_argument_test.cc index 7f5d2345aa7..deeefe165a0 100644 --- a/test/core/end2end/invalid_call_argument_test.cc +++ b/test/core/end2end/invalid_call_argument_test.cc @@ -24,6 +24,7 @@ #include #include +#include #include #include #include diff --git a/test/core/end2end/multiple_server_queues_test.cc b/test/core/end2end/multiple_server_queues_test.cc index daa8bb3c5fe..025f9f939af 100644 --- a/test/core/end2end/multiple_server_queues_test.cc +++ b/test/core/end2end/multiple_server_queues_test.cc @@ -16,6 +16,7 @@ // // +#include #include #include #include diff --git a/test/core/end2end/no_server_test.cc b/test/core/end2end/no_server_test.cc index 0a785d921ff..c6357f911cd 100644 --- a/test/core/end2end/no_server_test.cc +++ b/test/core/end2end/no_server_test.cc @@ -24,6 +24,7 @@ #include "absl/status/statusor.h" #include "absl/time/time.h" +#include #include #include #include diff --git a/test/core/end2end/tests/call_creds.cc b/test/core/end2end/tests/call_creds.cc index b90f681d0d2..ce6b949085f 100644 --- a/test/core/end2end/tests/call_creds.cc +++ b/test/core/end2end/tests/call_creds.cc @@ -21,6 +21,7 @@ #include "absl/types/optional.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/end2end/tests/filter_causes_close.cc b/test/core/end2end/tests/filter_causes_close.cc index ba73b4c581f..dc7fdafc667 100644 --- a/test/core/end2end/tests/filter_causes_close.cc +++ b/test/core/end2end/tests/filter_causes_close.cc @@ -102,13 +102,8 @@ const grpc_channel_filter test_filter = { return Immediate(ServerMetadataFromStatus( absl::PermissionDeniedError("Failure that's not preventable."))); }, - [](grpc_channel_element*, CallSpineInterface* args) { - args->client_initial_metadata().receiver.InterceptAndMap( - [args](ClientMetadataHandle) { - return args->Cancel( - ServerMetadataFromStatus(absl::PermissionDeniedError( - "Failure that's not preventable."))); - }); + [](grpc_channel_element*, CallSpineInterface*) { + Crash("Should never be called"); }, grpc_channel_next_op, sizeof(call_data), diff --git a/test/core/end2end/tests/http2_stats.cc b/test/core/end2end/tests/http2_stats.cc index b12d7a431a0..5e497f7b8f2 100644 --- a/test/core/end2end/tests/http2_stats.cc +++ b/test/core/end2end/tests/http2_stats.cc @@ -193,6 +193,9 @@ class NewFakeStatsPlugin : public FakeStatsPlugin { // This test verifies the HTTP2 stats on a stream CORE_END2END_TEST(Http2FullstackSingleHopTest, StreamStats) { + if (!IsHttp2StatsFixEnabled()) { + GTEST_SKIP() << "Test needs http2_stats_fix experiment to be enabled"; + } g_mu = new Mutex(); g_client_call_ended_notify = new Notification(); g_server_call_ended_notify = new Notification(); diff --git a/test/core/event_engine/event_engine_test_utils.h b/test/core/event_engine/event_engine_test_utils.h index 67bbe42d35d..debef7a0449 100644 --- a/test/core/event_engine/event_engine_test_utils.h +++ b/test/core/event_engine/event_engine_test_utils.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -159,6 +160,70 @@ class NotifyOnDelete { grpc_core::Notification* signal_; }; +// An endpoint implementation that supports Read and Write via std::threads. +// Passing a grpc_core::Notification will allow owners to know when all +// in-flight callbacks have been run, and all endpoint state has been destroyed. +class ThreadedNoopEndpoint : public EventEngine::Endpoint { + public: + explicit ThreadedNoopEndpoint(grpc_core::Notification* destroyed) + : state_(std::make_shared(destroyed)) {} + ~ThreadedNoopEndpoint() override { + std::thread deleter([state = state_]() { + CleanupThread(state->read); + CleanupThread(state->write); + }); + deleter.detach(); + } + + bool Read(absl::AnyInvocable on_read, SliceBuffer* buffer, + const ReadArgs* /* args */) override { + buffer->Clear(); + CleanupThread(state_->read); + state_->read = new std::thread([cb = std::move(on_read)]() mutable { + cb(absl::UnknownError("test")); + }); + return false; + } + + bool Write(absl::AnyInvocable on_writable, + SliceBuffer* data, const WriteArgs* /* args */) override { + data->Clear(); + CleanupThread(state_->write); + state_->write = new std::thread([cb = std::move(on_writable)]() mutable { + cb(absl::UnknownError("test")); + }); + return false; + } + + const EventEngine::ResolvedAddress& GetPeerAddress() const override { + return peer_; + } + + const EventEngine::ResolvedAddress& GetLocalAddress() const override { + return local_; + } + + private: + struct EndpointState { + explicit EndpointState(grpc_core::Notification* deleter) + : delete_notifier_(deleter) {} + std::thread* read = nullptr; + std::thread* write = nullptr; + NotifyOnDelete delete_notifier_; + }; + + static void CleanupThread(std::thread* thd) { + if (thd != nullptr) { + thd->join(); + delete thd; + } + } + + std::shared_ptr state_; + EventEngine::ResolvedAddress peer_; + EventEngine::ResolvedAddress local_; +}; + } // namespace experimental } // namespace grpc_event_engine diff --git a/test/core/filters/client_auth_filter_test.cc b/test/core/filters/client_auth_filter_test.cc index 4596cdee59f..bc06504b25f 100644 --- a/test/core/filters/client_auth_filter_test.cc +++ b/test/core/filters/client_auth_filter_test.cc @@ -21,6 +21,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/filters/filter_test.h b/test/core/filters/filter_test.h index 796b0a22213..c557e6aee16 100644 --- a/test/core/filters/filter_test.h +++ b/test/core/filters/filter_test.h @@ -231,7 +231,7 @@ class FilterTest : public FilterTestBase { absl::StatusOr MakeChannel(const ChannelArgs& args) { auto filter = Filter::Create(args, ChannelFilter::Args()); if (!filter.ok()) return filter.status(); - return Channel(std::make_unique(std::move(*filter)), this); + return Channel(std::move(*filter), this); } }; diff --git a/test/core/filters/filter_test_test.cc b/test/core/filters/filter_test_test.cc index e0dad7ad671..ec836316f86 100644 --- a/test/core/filters/filter_test_test.cc +++ b/test/core/filters/filter_test_test.cc @@ -49,9 +49,9 @@ class NoOpFilter final : public ChannelFilter { return next(std::move(args)); } - static absl::StatusOr Create(const ChannelArgs&, - ChannelFilter::Args) { - return NoOpFilter(); + static absl::StatusOr> Create( + const ChannelArgs&, ChannelFilter::Args) { + return std::make_unique(); } }; using NoOpFilterTest = FilterTest; @@ -70,9 +70,9 @@ class DelayStartFilter final : public ChannelFilter { next); } - static absl::StatusOr Create(const ChannelArgs&, - ChannelFilter::Args) { - return DelayStartFilter(); + static absl::StatusOr> Create( + const ChannelArgs&, ChannelFilter::Args) { + return std::make_unique(); } }; using DelayStartFilterTest = FilterTest; @@ -86,9 +86,9 @@ class AddClientInitialMetadataFilter final : public ChannelFilter { return next(std::move(args)); } - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs&, ChannelFilter::Args) { - return AddClientInitialMetadataFilter(); + return absl::make_unique(); } }; using AddClientInitialMetadataFilterTest = @@ -104,9 +104,9 @@ class AddServerTrailingMetadataFilter final : public ChannelFilter { }); } - static absl::StatusOr Create( - const ChannelArgs&, ChannelFilter::Args) { - return AddServerTrailingMetadataFilter(); + static absl::StatusOr> + Create(const ChannelArgs&, ChannelFilter::Args) { + return absl::make_unique(); } }; using AddServerTrailingMetadataFilterTest = @@ -122,10 +122,9 @@ class AddServerInitialMetadataFilter final : public ChannelFilter { }); return next(std::move(args)); } - - static absl::StatusOr Create( + static absl::StatusOr> Create( const ChannelArgs&, ChannelFilter::Args) { - return AddServerInitialMetadataFilter(); + return absl::make_unique(); } }; using AddServerInitialMetadataFilterTest = diff --git a/test/core/handshake/client_ssl.cc b/test/core/handshake/client_ssl.cc index 5540d3084e1..ce5951abacb 100644 --- a/test/core/handshake/client_ssl.cc +++ b/test/core/handshake/client_ssl.cc @@ -51,6 +51,7 @@ #include "absl/strings/str_cat.h" +#include #include #include #include diff --git a/test/core/handshake/server_ssl_common.cc b/test/core/handshake/server_ssl_common.cc index 0f0c4b195b1..b4a0ad1e828 100644 --- a/test/core/handshake/server_ssl_common.cc +++ b/test/core/handshake/server_ssl_common.cc @@ -36,6 +36,7 @@ #include "absl/base/thread_annotations.h" #include "absl/strings/str_cat.h" +#include #include #include #include diff --git a/test/core/handshake/verify_peer_options.cc b/test/core/handshake/verify_peer_options.cc index c9f47d39de6..fae7ffbb5fe 100644 --- a/test/core/handshake/verify_peer_options.cc +++ b/test/core/handshake/verify_peer_options.cc @@ -34,6 +34,7 @@ #include "absl/strings/str_cat.h" +#include #include #include #include diff --git a/test/core/http/httpcli_test.cc b/test/core/http/httpcli_test.cc index 8ed555af61b..7a8f3bf92b3 100644 --- a/test/core/http/httpcli_test.cc +++ b/test/core/http/httpcli_test.cc @@ -34,6 +34,7 @@ #include "absl/time/clock.h" #include "absl/time/time.h" +#include #include #include #include diff --git a/test/core/memory_usage/client.cc b/test/core/memory_usage/client.cc index 3b20c7193ed..61185fe361e 100644 --- a/test/core/memory_usage/client.cc +++ b/test/core/memory_usage/client.cc @@ -31,6 +31,7 @@ #include #include +#include #include #include #include diff --git a/test/core/memory_usage/server.cc b/test/core/memory_usage/server.cc index 7426e8b6a91..a789240f5b3 100644 --- a/test/core/memory_usage/server.cc +++ b/test/core/memory_usage/server.cc @@ -36,6 +36,7 @@ #include "absl/status/status.h" #include +#include #include #include #include diff --git a/test/core/security/BUILD b/test/core/security/BUILD index 2899bc9f523..58c2c6d63f5 100644 --- a/test/core/security/BUILD +++ b/test/core/security/BUILD @@ -95,7 +95,10 @@ grpc_cc_test( grpc_cc_test( name = "credentials_test", srcs = ["credentials_test.cc"], - external_deps = ["gtest"], + external_deps = [ + "absl/log:check", + "gtest", + ], language = "C++", deps = [ "//:gpr", diff --git a/test/core/security/alts_credentials_fuzzer.cc b/test/core/security/alts_credentials_fuzzer.cc index a11d362511f..1d47a506061 100644 --- a/test/core/security/alts_credentials_fuzzer.cc +++ b/test/core/security/alts_credentials_fuzzer.cc @@ -18,6 +18,7 @@ #include +#include #include #include #include diff --git a/test/core/security/create_jwt.cc b/test/core/security/create_jwt.cc index c645a30c792..edee063aa16 100644 --- a/test/core/security/create_jwt.cc +++ b/test/core/security/create_jwt.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include diff --git a/test/core/security/credentials_test.cc b/test/core/security/credentials_test.cc index 5afafcf50a3..70d8077282c 100644 --- a/test/core/security/credentials_test.cc +++ b/test/core/security/credentials_test.cc @@ -26,11 +26,13 @@ #include #include +#include "absl/log/check.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" +#include #include #include #include @@ -322,12 +324,11 @@ TEST(CredentialsTest, TestOauth2TokenFetcherCredsParsingOk) { absl::optional token_value; Duration token_lifetime; grpc_http_response response = http_response(200, valid_oauth2_json_response); - GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( - &response, &token_value, &token_lifetime) == - GRPC_CREDENTIALS_OK); - GPR_ASSERT(token_lifetime == Duration::Seconds(3599)); - GPR_ASSERT(token_value->as_string_view() == - "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"); + CHECK(grpc_oauth2_token_fetcher_credentials_parse_server_response( + &response, &token_value, &token_lifetime) == GRPC_CREDENTIALS_OK); + CHECK(token_lifetime == Duration::Seconds(3599)); + CHECK(token_value->as_string_view() == + "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"); grpc_http_response_destroy(&response); } @@ -336,9 +337,9 @@ TEST(CredentialsTest, TestOauth2TokenFetcherCredsParsingBadHttpStatus) { absl::optional token_value; Duration token_lifetime; grpc_http_response response = http_response(401, valid_oauth2_json_response); - GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( - &response, &token_value, &token_lifetime) == - GRPC_CREDENTIALS_ERROR); + CHECK(grpc_oauth2_token_fetcher_credentials_parse_server_response( + &response, &token_value, &token_lifetime) == + GRPC_CREDENTIALS_ERROR); grpc_http_response_destroy(&response); } @@ -347,9 +348,9 @@ TEST(CredentialsTest, TestOauth2TokenFetcherCredsParsingEmptyHttpBody) { absl::optional token_value; Duration token_lifetime; grpc_http_response response = http_response(200, ""); - GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( - &response, &token_value, &token_lifetime) == - GRPC_CREDENTIALS_ERROR); + CHECK(grpc_oauth2_token_fetcher_credentials_parse_server_response( + &response, &token_value, &token_lifetime) == + GRPC_CREDENTIALS_ERROR); grpc_http_response_destroy(&response); } @@ -362,9 +363,9 @@ TEST(CredentialsTest, TestOauth2TokenFetcherCredsParsingInvalidJson) { "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\"," " \"expires_in\":3599, " " \"token_type\":\"Bearer\""); - GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( - &response, &token_value, &token_lifetime) == - GRPC_CREDENTIALS_ERROR); + CHECK(grpc_oauth2_token_fetcher_credentials_parse_server_response( + &response, &token_value, &token_lifetime) == + GRPC_CREDENTIALS_ERROR); grpc_http_response_destroy(&response); } @@ -376,9 +377,9 @@ TEST(CredentialsTest, TestOauth2TokenFetcherCredsParsingMissingToken) { "{" " \"expires_in\":3599, " " \"token_type\":\"Bearer\"}"); - GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( - &response, &token_value, &token_lifetime) == - GRPC_CREDENTIALS_ERROR); + CHECK(grpc_oauth2_token_fetcher_credentials_parse_server_response( + &response, &token_value, &token_lifetime) == + GRPC_CREDENTIALS_ERROR); grpc_http_response_destroy(&response); } @@ -391,9 +392,9 @@ TEST(CredentialsTest, TestOauth2TokenFetcherCredsParsingMissingTokenType) { "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\"," " \"expires_in\":3599, " "}"); - GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( - &response, &token_value, &token_lifetime) == - GRPC_CREDENTIALS_ERROR); + CHECK(grpc_oauth2_token_fetcher_credentials_parse_server_response( + &response, &token_value, &token_lifetime) == + GRPC_CREDENTIALS_ERROR); grpc_http_response_destroy(&response); } @@ -405,9 +406,9 @@ TEST(CredentialsTest, TestOauth2TokenFetcherCredsParsingMissingTokenLifetime) { http_response(200, "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\"," " \"token_type\":\"Bearer\"}"); - GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response( - &response, &token_value, &token_lifetime) == - GRPC_CREDENTIALS_ERROR); + CHECK(grpc_oauth2_token_fetcher_credentials_parse_server_response( + &response, &token_value, &token_lifetime) == + GRPC_CREDENTIALS_ERROR); grpc_http_response_destroy(&response); } @@ -446,7 +447,7 @@ class RequestMetadataState : public RefCounted { &get_request_metadata_args_), [this](absl::StatusOr metadata) { if (metadata.ok()) { - GPR_ASSERT(metadata->get() == &md_); + CHECK(metadata->get() == &md_); } return metadata.status(); }); @@ -497,15 +498,15 @@ class RequestMetadataState : public RefCounted { StatusToString(expected_error_).c_str()); gpr_log(GPR_INFO, "actual_error: %s", StatusToString(error).c_str()); if (expected_error_.ok()) { - GPR_ASSERT(error.ok()); + CHECK_OK(error); } else { std::string expected_error; - GPR_ASSERT(grpc_error_get_str( - expected_error_, StatusStrProperty::kDescription, &expected_error)); + CHECK(grpc_error_get_str(expected_error_, StatusStrProperty::kDescription, + &expected_error)); std::string actual_error; - GPR_ASSERT(grpc_error_get_str(error, StatusStrProperty::kDescription, - &actual_error)); - GPR_ASSERT(expected_error == actual_error); + CHECK(grpc_error_get_str(error, StatusStrProperty::kDescription, + &actual_error)); + CHECK(expected_error == actual_error); } md_.Remove(HttpAuthorityMetadata()); md_.Remove(HttpPathMetadata()); @@ -536,7 +537,7 @@ TEST(CredentialsTest, TestGoogleIamCreds) { test_google_iam_authorization_token, test_google_iam_authority_selector, nullptr); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); creds->Unref(); @@ -548,9 +549,9 @@ TEST(CredentialsTest, TestAccessTokenCreds) { "authorization: Bearer blah"); grpc_call_credentials* creds = grpc_access_token_credentials_create("blah", nullptr); - GPR_ASSERT(creds->type() == grpc_access_token_credentials::Type()); + CHECK(creds->type() == grpc_access_token_credentials::Type()); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); creds->Unref(); @@ -561,9 +562,9 @@ class check_channel_oauth2 final : public grpc_channel_credentials { RefCountedPtr create_security_connector( RefCountedPtr call_creds, const char* /*target*/, ChannelArgs* /*new_args*/) override { - GPR_ASSERT(type() == Type()); - GPR_ASSERT(call_creds != nullptr); - GPR_ASSERT(call_creds->type() == grpc_access_token_credentials::Type()); + CHECK(type() == Type()); + CHECK(call_creds != nullptr); + CHECK(call_creds->type() == grpc_access_token_credentials::Type()); return nullptr; } @@ -611,7 +612,7 @@ TEST(CredentialsTest, TestOauth2GoogleIamCompositeCreds) { "authorization", test_oauth2_bearer_token); // Check security level of fake credentials. - GPR_ASSERT(oauth2_creds->min_security_level() == GRPC_SECURITY_NONE); + CHECK_EQ(oauth2_creds->min_security_level(), GRPC_SECURITY_NONE); grpc_call_credentials* google_iam_creds = grpc_google_iam_credentials_create( test_google_iam_authorization_token, test_google_iam_authority_selector, @@ -620,19 +621,17 @@ TEST(CredentialsTest, TestOauth2GoogleIamCompositeCreds) { grpc_composite_call_credentials_create(oauth2_creds, google_iam_creds, nullptr); // Check security level of composite credentials. - GPR_ASSERT(composite_creds->min_security_level() == - GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(composite_creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); oauth2_creds->Unref(); google_iam_creds->Unref(); - GPR_ASSERT(composite_creds->type() == - grpc_composite_call_credentials::Type()); + CHECK(composite_creds->type() == grpc_composite_call_credentials::Type()); const grpc_composite_call_credentials::CallCredentialsList& creds_list = static_cast(composite_creds) ->inner(); - GPR_ASSERT(creds_list.size() == 2); - GPR_ASSERT(creds_list[0]->type() == grpc_md_only_test_credentials::Type()); - GPR_ASSERT(creds_list[1]->type() == grpc_google_iam_credentials::Type()); + CHECK_EQ(creds_list.size(), 2); + CHECK(creds_list[0]->type() == grpc_md_only_test_credentials::Type()); + CHECK(creds_list[1]->type() == grpc_google_iam_credentials::Type()); state->RunRequestMetadataTest(composite_creds, kTestUrlScheme, kTestAuthority, kTestPath); composite_creds->Unref(); @@ -643,14 +642,14 @@ class check_channel_oauth2_google_iam final : public grpc_channel_credentials { RefCountedPtr create_security_connector( RefCountedPtr call_creds, const char* /*target*/, ChannelArgs* /*new_args*/) override { - GPR_ASSERT(type() == Type()); - GPR_ASSERT(call_creds != nullptr); - GPR_ASSERT(call_creds->type() == grpc_composite_call_credentials::Type()); + CHECK(type() == Type()); + CHECK(call_creds != nullptr); + CHECK(call_creds->type() == grpc_composite_call_credentials::Type()); const grpc_composite_call_credentials::CallCredentialsList& creds_list = static_cast(call_creds.get()) ->inner(); - GPR_ASSERT(creds_list[0]->type() == grpc_access_token_credentials::Type()); - GPR_ASSERT(creds_list[1]->type() == grpc_google_iam_credentials::Type()); + CHECK(creds_list[0]->type() == grpc_access_token_credentials::Type()); + CHECK(creds_list[1]->type() == grpc_google_iam_credentials::Type()); return nullptr; } @@ -699,14 +698,14 @@ TEST(CredentialsTest, TestChannelOauth2GoogleIamCompositeCreds) { void validate_compute_engine_http_request(const grpc_http_request* request, const char* host, const char* path) { - GPR_ASSERT(strcmp(host, "metadata.google.internal.") == 0); - GPR_ASSERT( + CHECK_EQ(strcmp(host, "metadata.google.internal."), 0); + CHECK_EQ( strcmp(path, - "/computeMetadata/v1/instance/service-accounts/default/token") == + "/computeMetadata/v1/instance/service-accounts/default/token"), 0); - GPR_ASSERT(request->hdr_count == 1); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Metadata-Flavor") == 0); - GPR_ASSERT(strcmp(request->hdrs[0].value, "Google") == 0); + CHECK_EQ(request->hdr_count, 1); + CHECK_EQ(strcmp(request->hdrs[0].key, "Metadata-Flavor"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "Google"), 0); } int compute_engine_httpcli_get_success_override( @@ -734,7 +733,7 @@ int httpcli_post_should_not_be_called( const char* /*path*/, const char* /*body_bytes*/, size_t /*body_size*/, Timestamp /*deadline*/, grpc_closure* /*on_done*/, grpc_http_response* /*response*/) { - GPR_ASSERT("HTTP POST should not be called" == nullptr); + CHECK(false) << "HTTP POST should not be called"; return 1; } @@ -743,7 +742,7 @@ int httpcli_get_should_not_be_called(const grpc_http_request* /*request*/, Timestamp /*deadline*/, grpc_closure* /*on_done*/, grpc_http_response* /*response*/) { - GPR_ASSERT("HTTP GET should not be called" == nullptr); + CHECK(false) << "HTTP GET should not be called"; return 1; } @@ -754,7 +753,7 @@ int httpcli_put_should_not_be_called(const grpc_http_request* /*request*/, Timestamp /*deadline*/, grpc_closure* /*on_done*/, grpc_http_response* /*response*/) { - GPR_ASSERT("HTTP PUT should not be called" == nullptr); + CHECK(false) << "HTTP PUT should not be called"; return 1; } @@ -767,7 +766,7 @@ TEST(CredentialsTest, TestComputeEngineCredsSuccess) { grpc_call_credentials* creds = grpc_google_compute_engine_credentials_create(nullptr); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); // First request: http get should be called. auto state = RequestMetadataState::NewInstance(absl::OkStatus(), emd); @@ -787,8 +786,8 @@ TEST(CredentialsTest, TestComputeEngineCredsSuccess) { kTestPath); ExecCtx::Get()->Flush(); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); } @@ -807,8 +806,8 @@ TEST(CredentialsTest, TestComputeEngineCredsFailure) { httpcli_put_should_not_be_called); state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); } @@ -817,20 +816,20 @@ void validate_refresh_token_http_request(const grpc_http_request* request, const char* host, const char* path, const char* body, size_t body_size) { // The content of the assertion is tested extensively in json_token_test. - GPR_ASSERT(body != nullptr); - GPR_ASSERT(body_size != 0); + CHECK_NE(body, nullptr); + CHECK_NE(body_size, 0); std::string expected_body = absl::StrFormat( GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING, "32555999999.apps.googleusercontent.com", "EmssLNjJy1332hD4KFsecret", "1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42"); - GPR_ASSERT(expected_body.size() == body_size); - GPR_ASSERT(memcmp(expected_body.data(), body, body_size) == 0); - GPR_ASSERT(strcmp(host, GRPC_GOOGLE_OAUTH2_SERVICE_HOST) == 0); - GPR_ASSERT(strcmp(path, GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH) == 0); - GPR_ASSERT(request->hdr_count == 1); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Content-Type") == 0); - GPR_ASSERT( - strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded") == 0); + CHECK_EQ(expected_body.size(), body_size); + CHECK_EQ(memcmp(expected_body.data(), body, body_size), 0); + CHECK_EQ(strcmp(host, GRPC_GOOGLE_OAUTH2_SERVICE_HOST), 0); + CHECK_EQ(strcmp(path, GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH), 0); + CHECK_EQ(request->hdr_count, 1); + CHECK_EQ(strcmp(request->hdrs[0].key, "Content-Type"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded"), + 0); } int refresh_token_httpcli_post_success(const grpc_http_request* request, @@ -865,7 +864,7 @@ TEST(CredentialsTest, TestRefreshTokenCredsSuccess) { test_refresh_token_str, nullptr); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); // First request: http put should be called. auto state = RequestMetadataState::NewInstance(absl::OkStatus(), emd); @@ -884,8 +883,8 @@ TEST(CredentialsTest, TestRefreshTokenCredsSuccess) { state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); ExecCtx::Get()->Flush(); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); @@ -905,8 +904,8 @@ TEST(CredentialsTest, TestRefreshTokenCredsFailure) { httpcli_put_should_not_be_called); state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); @@ -925,12 +924,12 @@ TEST(CredentialsTest, TestValidStsCredsOptions) { nullptr // actor_token_type }; absl::StatusOr sts_url = ValidateStsCredentialsOptions(&valid_options); - GPR_ASSERT(sts_url.ok()); + CHECK_OK(sts_url); absl::string_view host; absl::string_view port; - GPR_ASSERT(SplitHostPort(sts_url->authority(), &host, &port)); - GPR_ASSERT(host == "foo.com"); - GPR_ASSERT(port == "5555"); + CHECK(SplitHostPort(sts_url->authority(), &host, &port)); + CHECK(host == "foo.com"); + CHECK(port == "5555"); } TEST(CredentialsTest, TestInvalidStsCredsOptions) { @@ -947,7 +946,7 @@ TEST(CredentialsTest, TestInvalidStsCredsOptions) { }; absl::StatusOr url_should_be_invalid = ValidateStsCredentialsOptions(&invalid_options); - GPR_ASSERT(!url_should_be_invalid.ok()); + CHECK(!url_should_be_invalid.ok()); invalid_options = { test_sts_endpoint_url, // sts_endpoint_url @@ -961,7 +960,7 @@ TEST(CredentialsTest, TestInvalidStsCredsOptions) { nullptr // actor_token_type }; url_should_be_invalid = ValidateStsCredentialsOptions(&invalid_options); - GPR_ASSERT(!url_should_be_invalid.ok()); + CHECK(!url_should_be_invalid.ok()); invalid_options = { nullptr, // sts_endpoint_url (Required) @@ -975,7 +974,7 @@ TEST(CredentialsTest, TestInvalidStsCredsOptions) { nullptr // actor_token_type }; url_should_be_invalid = ValidateStsCredentialsOptions(&invalid_options); - GPR_ASSERT(!url_should_be_invalid.ok()); + CHECK(!url_should_be_invalid.ok()); invalid_options = { "not_a_valid_uri", // sts_endpoint_url @@ -989,7 +988,7 @@ TEST(CredentialsTest, TestInvalidStsCredsOptions) { nullptr // actor_token_type }; url_should_be_invalid = ValidateStsCredentialsOptions(&invalid_options); - GPR_ASSERT(!url_should_be_invalid.ok()); + CHECK(!url_should_be_invalid.ok()); invalid_options = { "ftp://ftp.is.not.a.valid.scheme/bar", // sts_endpoint_url @@ -1003,18 +1002,18 @@ TEST(CredentialsTest, TestInvalidStsCredsOptions) { nullptr // actor_token_type }; url_should_be_invalid = ValidateStsCredentialsOptions(&invalid_options); - GPR_ASSERT(!url_should_be_invalid.ok()); + CHECK(!url_should_be_invalid.ok()); } void assert_query_parameters(const URI& uri, absl::string_view expected_key, absl::string_view expected_val) { const auto it = uri.query_parameter_map().find(expected_key); - GPR_ASSERT(it != uri.query_parameter_map().end()); + CHECK(it != uri.query_parameter_map().end()); if (it->second != expected_val) { gpr_log(GPR_ERROR, "%s!=%s", std::string(it->second).c_str(), std::string(expected_val).c_str()); } - GPR_ASSERT(it->second == expected_val); + CHECK(it->second == expected_val); } void validate_sts_token_http_request(const grpc_http_request* request, @@ -1022,14 +1021,14 @@ void validate_sts_token_http_request(const grpc_http_request* request, const char* body, size_t body_size, bool expect_actor_token) { // Check that the body is constructed properly. - GPR_ASSERT(body != nullptr); - GPR_ASSERT(body_size != 0); + CHECK_NE(body, nullptr); + CHECK_NE(body_size, 0); std::string get_url_equivalent = absl::StrFormat("%s?%s", test_sts_endpoint_url, body); absl::StatusOr url = URI::Parse(get_url_equivalent); if (!url.ok()) { gpr_log(GPR_ERROR, "%s", url.status().ToString().c_str()); - GPR_ASSERT(url.ok()); + CHECK_OK(url); } assert_query_parameters(*url, "resource", "resource"); assert_query_parameters(*url, "audience", "audience"); @@ -1043,19 +1042,19 @@ void validate_sts_token_http_request(const grpc_http_request* request, assert_query_parameters(*url, "actor_token_type", test_signed_jwt_token_type2); } else { - GPR_ASSERT(url->query_parameter_map().find("actor_token") == - url->query_parameter_map().end()); - GPR_ASSERT(url->query_parameter_map().find("actor_token_type") == - url->query_parameter_map().end()); + CHECK(url->query_parameter_map().find("actor_token") == + url->query_parameter_map().end()); + CHECK(url->query_parameter_map().find("actor_token_type") == + url->query_parameter_map().end()); } // Check the rest of the request. - GPR_ASSERT(strcmp(host, "foo.com:5555") == 0); - GPR_ASSERT(strcmp(path, "/v1/token-exchange") == 0); - GPR_ASSERT(request->hdr_count == 1); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Content-Type") == 0); - GPR_ASSERT( - strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded") == 0); + CHECK_EQ(strcmp(host, "foo.com:5555"), 0); + CHECK_EQ(strcmp(path, "/v1/token-exchange"), 0); + CHECK_EQ(request->hdr_count, 1); + CHECK_EQ(strcmp(request->hdrs[0].key, "Content-Type"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded"), + 0); } int sts_token_httpcli_post_success(const grpc_http_request* request, @@ -1083,10 +1082,10 @@ int sts_token_httpcli_post_success_no_actor_token( char* write_tmp_jwt_file(const char* jwt_contents) { char* path; FILE* tmp = gpr_tmpfile(test_signed_jwt_path_prefix, &path); - GPR_ASSERT(path != nullptr); - GPR_ASSERT(tmp != nullptr); + CHECK_NE(path, nullptr); + CHECK_NE(tmp, nullptr); size_t jwt_length = strlen(jwt_contents); - GPR_ASSERT(fwrite(jwt_contents, 1, jwt_length, tmp) == jwt_length); + CHECK_EQ(fwrite(jwt_contents, 1, jwt_length, tmp), jwt_length); fclose(tmp); return path; } @@ -1114,7 +1113,7 @@ TEST(CredentialsTest, TestStsCredsSuccess) { grpc_sts_credentials_create(&valid_options, nullptr); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); // First request: http put should be called. auto state = RequestMetadataState::NewInstance(absl::OkStatus(), emd); @@ -1133,8 +1132,8 @@ TEST(CredentialsTest, TestStsCredsSuccess) { state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); ExecCtx::Get()->Flush(); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); @@ -1159,7 +1158,7 @@ TEST(CredentialsTest, TestStsCredsTokenFileNotFound) { grpc_sts_credentials_create(&valid_options, nullptr); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( GRPC_ERROR_CREATE("Error occurred when fetching oauth2 token."), {}); @@ -1197,7 +1196,7 @@ TEST(CredentialsTest, TestStsCredsNoActorTokenSuccess) { grpc_sts_credentials_create(&valid_options, nullptr); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); // First request: http put should be called. auto state = RequestMetadataState::NewInstance(absl::OkStatus(), emd); @@ -1216,8 +1215,8 @@ TEST(CredentialsTest, TestStsCredsNoActorTokenSuccess) { state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); ExecCtx::Get()->Flush(); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); @@ -1249,8 +1248,8 @@ TEST(CredentialsTest, TestStsCredsLoadTokenFailure) { httpcli_put_should_not_be_called); state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); @@ -1283,8 +1282,8 @@ TEST(CredentialsTest, TestStsCredsHttpFailure) { httpcli_put_should_not_be_called); state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); gpr_free(test_signed_jwt_path); @@ -1293,30 +1292,30 @@ TEST(CredentialsTest, TestStsCredsHttpFailure) { void validate_jwt_encode_and_sign_params(const grpc_auth_json_key* json_key, const char* scope, gpr_timespec token_lifetime) { - GPR_ASSERT(grpc_auth_json_key_is_valid(json_key)); - GPR_ASSERT(json_key->private_key != nullptr); + CHECK(grpc_auth_json_key_is_valid(json_key)); + CHECK_NE(json_key->private_key, nullptr); #if OPENSSL_VERSION_NUMBER < 0x30000000L - GPR_ASSERT(RSA_check_key(json_key->private_key)); + CHECK(RSA_check_key(json_key->private_key)); #else EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new(json_key->private_key, NULL); - GPR_ASSERT(EVP_PKEY_private_check(ctx)); + CHECK(EVP_PKEY_private_check(ctx)); EVP_PKEY_CTX_free(ctx); #endif - GPR_ASSERT(json_key->type != nullptr && - strcmp(json_key->type, "service_account") == 0); - GPR_ASSERT(json_key->private_key_id != nullptr && - strcmp(json_key->private_key_id, - "e6b5137873db8d2ef81e06a47289e6434ec8a165") == 0); - GPR_ASSERT(json_key->client_id != nullptr && - strcmp(json_key->client_id, - "777-abaslkan11hlb6nmim3bpspl31ud.apps." - "googleusercontent.com") == 0); - GPR_ASSERT(json_key->client_email != nullptr && - strcmp(json_key->client_email, - "777-abaslkan11hlb6nmim3bpspl31ud@developer." - "gserviceaccount.com") == 0); - if (scope != nullptr) GPR_ASSERT(strcmp(scope, test_scope) == 0); - GPR_ASSERT(gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()) == 0); + CHECK(json_key->type != nullptr && + strcmp(json_key->type, "service_account") == 0); + CHECK(json_key->private_key_id != nullptr && + strcmp(json_key->private_key_id, + "e6b5137873db8d2ef81e06a47289e6434ec8a165") == 0); + CHECK(json_key->client_id != nullptr && + strcmp(json_key->client_id, + "777-abaslkan11hlb6nmim3bpspl31ud.apps." + "googleusercontent.com") == 0); + CHECK(json_key->client_email != nullptr && + strcmp(json_key->client_email, + "777-abaslkan11hlb6nmim3bpspl31ud@developer." + "gserviceaccount.com") == 0); + if (scope != nullptr) CHECK_EQ(strcmp(scope, test_scope), 0); + CHECK_EQ(gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()), 0); } char* encode_and_sign_jwt_success(const grpc_auth_json_key* json_key, @@ -1342,15 +1341,14 @@ char* encode_and_sign_jwt_failure(const grpc_auth_json_key* json_key, char* encode_and_sign_jwt_should_not_be_called( const grpc_auth_json_key* /*json_key*/, const char* /*audience*/, gpr_timespec /*token_lifetime*/, const char* /*scope*/) { - GPR_ASSERT("grpc_jwt_encode_and_sign should not be called" == nullptr); + CHECK_EQ("grpc_jwt_encode_and_sign should not be called", nullptr); return nullptr; } grpc_service_account_jwt_access_credentials* creds_as_jwt( grpc_call_credentials* creds) { - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(creds->type() == - grpc_service_account_jwt_access_credentials::Type()); + CHECK(creds != nullptr); + CHECK(creds->type() == grpc_service_account_jwt_access_credentials::Type()); return reinterpret_cast(creds); } @@ -1362,25 +1360,28 @@ TEST(CredentialsTest, TestJwtCredsLifetime) { grpc_call_credentials* jwt_creds = grpc_service_account_jwt_access_credentials_create( json_key_string, grpc_max_auth_token_lifetime(), nullptr); - GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(), - grpc_max_auth_token_lifetime()) == 0); + CHECK_EQ(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(), + grpc_max_auth_token_lifetime()), + 0); // Check security level. - GPR_ASSERT(jwt_creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); - GPR_ASSERT(strncmp(expected_creds_debug_string_prefix, - jwt_creds->debug_string().c_str(), - strlen(expected_creds_debug_string_prefix)) == 0); + CHECK_EQ(jwt_creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(strncmp(expected_creds_debug_string_prefix, + jwt_creds->debug_string().c_str(), + strlen(expected_creds_debug_string_prefix)), + 0); grpc_call_credentials_release(jwt_creds); // Shorter lifetime. gpr_timespec token_lifetime = {10, 0, GPR_TIMESPAN}; - GPR_ASSERT(gpr_time_cmp(grpc_max_auth_token_lifetime(), token_lifetime) > 0); + CHECK_GT(gpr_time_cmp(grpc_max_auth_token_lifetime(), token_lifetime), 0); jwt_creds = grpc_service_account_jwt_access_credentials_create( json_key_string, token_lifetime, nullptr); - GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(), - token_lifetime) == 0); - GPR_ASSERT(strncmp(expected_creds_debug_string_prefix, - jwt_creds->debug_string().c_str(), - strlen(expected_creds_debug_string_prefix)) == 0); + CHECK_EQ( + gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(), token_lifetime), 0); + CHECK_EQ(strncmp(expected_creds_debug_string_prefix, + jwt_creds->debug_string().c_str(), + strlen(expected_creds_debug_string_prefix)), + 0); grpc_call_credentials_release(jwt_creds); // Cropped lifetime. @@ -1388,11 +1389,11 @@ TEST(CredentialsTest, TestJwtCredsLifetime) { token_lifetime = gpr_time_add(grpc_max_auth_token_lifetime(), add_to_max); jwt_creds = grpc_service_account_jwt_access_credentials_create( json_key_string, token_lifetime, nullptr); - GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(), - grpc_max_auth_token_lifetime()) == 0); - GPR_ASSERT(strncmp(expected_creds_debug_string_prefix, - jwt_creds->debug_string().c_str(), - strlen(expected_creds_debug_string_prefix)) == 0); + CHECK(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(), + grpc_max_auth_token_lifetime()) == 0); + CHECK(strncmp(expected_creds_debug_string_prefix, + jwt_creds->debug_string().c_str(), + strlen(expected_creds_debug_string_prefix)) == 0); grpc_call_credentials_release(jwt_creds); gpr_free(json_key_string); @@ -1400,12 +1401,12 @@ TEST(CredentialsTest, TestJwtCredsLifetime) { TEST(CredentialsTest, TestRemoveServiceFromJwtUri) { const char wrong_uri[] = "hello world"; - GPR_ASSERT(!RemoveServiceNameFromJwtUri(wrong_uri).ok()); + CHECK(!RemoveServiceNameFromJwtUri(wrong_uri).ok()); const char valid_uri[] = "https://foo.com/get/"; const char expected_uri[] = "https://foo.com/"; auto output = RemoveServiceNameFromJwtUri(valid_uri); - GPR_ASSERT(output.ok()); - GPR_ASSERT(strcmp(output->c_str(), expected_uri) == 0); + CHECK_OK(output); + CHECK_EQ(strcmp(output->c_str(), expected_uri), 0); } TEST(CredentialsTest, TestJwtCredsSuccess) { @@ -1442,9 +1443,10 @@ TEST(CredentialsTest, TestJwtCredsSuccess) { state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestOtherAuthority, kTestOtherPath); ExecCtx::Get()->Flush(); - GPR_ASSERT(strncmp(expected_creds_debug_string_prefix, - creds->debug_string().c_str(), - strlen(expected_creds_debug_string_prefix)) == 0); + CHECK_EQ( + strncmp(expected_creds_debug_string_prefix, creds->debug_string().c_str(), + strlen(expected_creds_debug_string_prefix)), + 0); creds->Unref(); gpr_free(json_key_string); @@ -1467,9 +1469,10 @@ TEST(CredentialsTest, TestJwtCredsSigningFailure) { kTestPath); gpr_free(json_key_string); - GPR_ASSERT(strncmp(expected_creds_debug_string_prefix, - creds->debug_string().c_str(), - strlen(expected_creds_debug_string_prefix)) == 0); + CHECK_EQ( + strncmp(expected_creds_debug_string_prefix, creds->debug_string().c_str(), + strlen(expected_creds_debug_string_prefix)), + 0); creds->Unref(); grpc_jwt_encode_and_sign_set_override(nullptr); @@ -1480,9 +1483,9 @@ void set_google_default_creds_env_var_with_file_contents( size_t contents_len = strlen(contents); char* creds_file_name; FILE* creds_file = gpr_tmpfile(file_prefix, &creds_file_name); - GPR_ASSERT(creds_file_name != nullptr); - GPR_ASSERT(creds_file != nullptr); - GPR_ASSERT(fwrite(contents, 1, contents_len, creds_file) == contents_len); + CHECK_NE(creds_file_name, nullptr); + CHECK_NE(creds_file, nullptr); + CHECK_EQ(fwrite(contents, 1, contents_len, creds_file), contents_len); fclose(creds_file); SetEnv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, creds_file_name); gpr_free(creds_file_name); @@ -1513,15 +1516,15 @@ TEST(CredentialsTest, TestGoogleDefaultCredsAuthKey) { auto* default_creds = reinterpret_cast( creds->inner_creds()); - GPR_ASSERT(default_creds->ssl_creds() != nullptr); + CHECK_NE(default_creds->ssl_creds(), nullptr); auto* jwt = reinterpret_cast( creds->call_creds()); - GPR_ASSERT( + CHECK_EQ( strcmp(jwt->key().client_id, - "777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent.com") == + "777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent.com"), 0); - GPR_ASSERT(g_test_gce_tenancy_checker_called == false); + CHECK_EQ(g_test_gce_tenancy_checker_called, false); creds->Unref(); SetEnv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); // Reset. grpc_override_well_known_credentials_path_getter(nullptr); @@ -1540,12 +1543,13 @@ TEST(CredentialsTest, TestGoogleDefaultCredsRefreshToken) { auto* default_creds = reinterpret_cast( creds->inner_creds()); - GPR_ASSERT(default_creds->ssl_creds() != nullptr); + CHECK_NE(default_creds->ssl_creds(), nullptr); auto* refresh = reinterpret_cast( creds->call_creds()); - GPR_ASSERT(strcmp(refresh->refresh_token().client_id, - "32555999999.apps.googleusercontent.com") == 0); + CHECK_EQ(strcmp(refresh->refresh_token().client_id, + "32555999999.apps.googleusercontent.com"), + 0); creds->Unref(); SetEnv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); // Reset. grpc_override_well_known_credentials_path_getter(nullptr); @@ -1565,10 +1569,10 @@ TEST(CredentialsTest, TestGoogleDefaultCredsExternalAccountCredentialsPscSts) { auto* default_creds = reinterpret_cast( creds->inner_creds()); - GPR_ASSERT(default_creds->ssl_creds() != nullptr); + CHECK_NE(default_creds->ssl_creds(), nullptr); auto* external = reinterpret_cast(creds->call_creds()); - GPR_ASSERT(external != nullptr); + CHECK_NE(external, nullptr); creds->Unref(); SetEnv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); // Reset. grpc_override_well_known_credentials_path_getter(nullptr); @@ -1588,10 +1592,10 @@ TEST(CredentialsTest, TestGoogleDefaultCredsExternalAccountCredentialsPscIam) { auto* default_creds = reinterpret_cast( creds->inner_creds()); - GPR_ASSERT(default_creds->ssl_creds() != nullptr); + CHECK_NE(default_creds->ssl_creds(), nullptr); auto* external = reinterpret_cast(creds->call_creds()); - GPR_ASSERT(external != nullptr); + CHECK_NE(external, nullptr); creds->Unref(); SetEnv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); // Reset. grpc_override_well_known_credentials_path_getter(nullptr); @@ -1608,8 +1612,8 @@ int default_creds_metadata_server_detection_httpcli_get_success_override( headers[0].value = gpr_strdup("Google"); response->hdr_count = 1; response->hdrs = headers; - GPR_ASSERT(strcmp(path, "/") == 0); - GPR_ASSERT(strcmp(host, "metadata.google.internal.") == 0); + CHECK_EQ(strcmp(path, "/"), 0); + CHECK_EQ(strcmp(host, "metadata.google.internal."), 0); ExecCtx::Run(DEBUG_LOCATION, on_done, absl::OkStatus()); return 1; } @@ -1633,8 +1637,8 @@ TEST(CredentialsTest, TestGoogleDefaultCredsGce) { grpc_google_default_credentials_create(nullptr)); // Verify that the default creds actually embeds a GCE creds. - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(creds->call_creds() != nullptr); + CHECK(creds != nullptr); + CHECK_NE(creds->call_creds(), nullptr); HttpRequest::SetOverride(compute_engine_httpcli_get_success_override, httpcli_post_should_not_be_called, httpcli_put_should_not_be_called); @@ -1642,7 +1646,7 @@ TEST(CredentialsTest, TestGoogleDefaultCredsGce) { kTestAuthority, kTestPath); ExecCtx::Get()->Flush(); - GPR_ASSERT(g_test_gce_tenancy_checker_called == true); + CHECK_EQ(g_test_gce_tenancy_checker_called, true); // Cleanup. creds->Unref(); @@ -1670,15 +1674,15 @@ TEST(CredentialsTest, TestGoogleDefaultCredsNonGce) { reinterpret_cast( grpc_google_default_credentials_create(nullptr)); // Verify that the default creds actually embeds a GCE creds. - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(creds->call_creds() != nullptr); + CHECK(creds != nullptr); + CHECK_NE(creds->call_creds(), nullptr); HttpRequest::SetOverride(compute_engine_httpcli_get_success_override, httpcli_post_should_not_be_called, httpcli_put_should_not_be_called); state->RunRequestMetadataTest(creds->mutable_call_creds(), kTestUrlScheme, kTestAuthority, kTestPath); ExecCtx::Get()->Flush(); - GPR_ASSERT(g_test_gce_tenancy_checker_called == true); + CHECK_EQ(g_test_gce_tenancy_checker_called, true); // Cleanup. creds->Unref(); HttpRequest::SetOverride(nullptr, nullptr, nullptr); @@ -1690,8 +1694,8 @@ int default_creds_gce_detection_httpcli_get_failure_override( Timestamp /*deadline*/, grpc_closure* on_done, grpc_http_response* response) { // No magic header. - GPR_ASSERT(strcmp(path, "/") == 0); - GPR_ASSERT(strcmp(host, "metadata.google.internal.") == 0); + CHECK_EQ(strcmp(path, "/"), 0); + CHECK_EQ(strcmp(host, "metadata.google.internal."), 0); *response = http_response(200, ""); ExecCtx::Run(DEBUG_LOCATION, on_done, absl::OkStatus()); return 1; @@ -1709,11 +1713,11 @@ TEST(CredentialsTest, TestNoGoogleDefaultCreds) { default_creds_gce_detection_httpcli_get_failure_override, httpcli_post_should_not_be_called, httpcli_put_should_not_be_called); // Simulate a successful detection of GCE. - GPR_ASSERT(grpc_google_default_credentials_create(nullptr) == nullptr); + CHECK_EQ(grpc_google_default_credentials_create(nullptr), nullptr); // Try a second one. GCE detection should occur again. g_test_gce_tenancy_checker_called = false; - GPR_ASSERT(grpc_google_default_credentials_create(nullptr) == nullptr); - GPR_ASSERT(g_test_gce_tenancy_checker_called == true); + CHECK_EQ(grpc_google_default_credentials_create(nullptr), nullptr); + CHECK_EQ(g_test_gce_tenancy_checker_called, true); // Cleanup. grpc_override_well_known_credentials_path_getter(nullptr); HttpRequest::SetOverride(nullptr, nullptr, nullptr); @@ -1736,9 +1740,9 @@ TEST(CredentialsTest, TestGoogleDefaultCredsCallCredsSpecified) { grpc_composite_channel_credentials* channel_creds = reinterpret_cast( grpc_google_default_credentials_create(call_creds)); - GPR_ASSERT(g_test_gce_tenancy_checker_called == false); - GPR_ASSERT(channel_creds != nullptr); - GPR_ASSERT(channel_creds->call_creds() != nullptr); + CHECK_EQ(g_test_gce_tenancy_checker_called, false); + CHECK_NE(channel_creds, nullptr); + CHECK_NE(channel_creds->call_creds(), nullptr); HttpRequest::SetOverride(compute_engine_httpcli_get_success_override, httpcli_post_should_not_be_called, httpcli_put_should_not_be_called); @@ -1786,9 +1790,9 @@ TEST(CredentialsTest, TestGoogleDefaultCredsNotDefault) { grpc_composite_channel_credentials* channel_creds = reinterpret_cast( grpc_google_default_credentials_create(call_creds.release())); - GPR_ASSERT(g_test_gce_tenancy_checker_called == false); - GPR_ASSERT(channel_creds != nullptr); - GPR_ASSERT(channel_creds->call_creds() != nullptr); + CHECK_EQ(g_test_gce_tenancy_checker_called, false); + CHECK_NE(channel_creds, nullptr); + CHECK_NE(channel_creds->call_creds(), nullptr); state->RunRequestMetadataTest(channel_creds->mutable_call_creds(), kTestUrlScheme, kTestAuthority, kTestPath); ExecCtx::Get()->Flush(); @@ -1811,11 +1815,11 @@ int plugin_get_metadata_success( grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], size_t* num_creds_md, grpc_status_code* /*status*/, const char** /*error_details*/) { - GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0); - GPR_ASSERT(strcmp(context.method_name, test_method) == 0); - GPR_ASSERT(context.channel_auth_context == nullptr); - GPR_ASSERT(context.reserved == nullptr); - GPR_ASSERT(plugin_md.size() < GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX); + CHECK_EQ(strcmp(context.service_url, test_service_url), 0); + CHECK_EQ(strcmp(context.method_name, test_method), 0); + CHECK_EQ(context.channel_auth_context, nullptr); + CHECK_EQ(context.reserved, nullptr); + CHECK_LT(plugin_md.size(), GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX); plugin_state* s = static_cast(state); *s = PLUGIN_GET_METADATA_CALLED_STATE; size_t i = 0; @@ -1837,10 +1841,10 @@ int plugin_get_metadata_failure( grpc_metadata /*creds_md*/[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], size_t* /*num_creds_md*/, grpc_status_code* status, const char** error_details) { - GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0); - GPR_ASSERT(strcmp(context.method_name, test_method) == 0); - GPR_ASSERT(context.channel_auth_context == nullptr); - GPR_ASSERT(context.reserved == nullptr); + CHECK_EQ(strcmp(context.service_url, test_service_url), 0); + CHECK_EQ(strcmp(context.method_name, test_method), 0); + CHECK_EQ(context.channel_auth_context, nullptr); + CHECK_EQ(context.reserved, nullptr); plugin_state* s = static_cast(state); *s = PLUGIN_GET_METADATA_CALLED_STATE; *status = GRPC_STATUS_UNAUTHENTICATED; @@ -1890,16 +1894,16 @@ TEST(CredentialsTest, TestMetadataPluginSuccess) { grpc_call_credentials* creds = grpc_metadata_credentials_create_from_plugin( plugin, GRPC_PRIVACY_AND_INTEGRITY, nullptr); // Check security level. - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); - GPR_ASSERT(state == PLUGIN_INITIAL_STATE); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(state, PLUGIN_INITIAL_STATE); md_state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); - GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(state, PLUGIN_GET_METADATA_CALLED_STATE); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); - GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE); + CHECK_EQ(state, PLUGIN_DESTROY_CALLED_STATE); } TEST(CredentialsTest, TestMetadataPluginFailure) { @@ -1922,15 +1926,15 @@ TEST(CredentialsTest, TestMetadataPluginFailure) { grpc_call_credentials* creds = grpc_metadata_credentials_create_from_plugin( plugin, GRPC_PRIVACY_AND_INTEGRITY, nullptr); - GPR_ASSERT(state == PLUGIN_INITIAL_STATE); + CHECK_EQ(state, PLUGIN_INITIAL_STATE); md_state->RunRequestMetadataTest(creds, kTestUrlScheme, kTestAuthority, kTestPath); - GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE); - GPR_ASSERT( - strcmp(creds->debug_string().c_str(), expected_creds_debug_string) == 0); + CHECK_EQ(state, PLUGIN_GET_METADATA_CALLED_STATE); + CHECK_EQ(strcmp(creds->debug_string().c_str(), expected_creds_debug_string), + 0); creds->Unref(); - GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE); + CHECK_EQ(state, PLUGIN_DESTROY_CALLED_STATE); } TEST(CredentialsTest, TestGetWellKnownGoogleCredentialsFilePath) { @@ -1945,12 +1949,12 @@ TEST(CredentialsTest, TestGetWellKnownGoogleCredentialsFilePath) { #endif // defined(GRPC_BAZEL_BUILD) && (defined(GPR_POSIX_ENV) || // defined(GPR_LINUX_ENV)) std::string path = grpc_get_well_known_google_credentials_file_path(); - GPR_ASSERT(!path.empty()); + CHECK(!path.empty()); #if defined(GPR_POSIX_ENV) || defined(GPR_LINUX_ENV) restore_home_env = true; UnsetEnv("HOME"); path = grpc_get_well_known_google_credentials_file_path(); - GPR_ASSERT(path.empty()); + CHECK(path.empty()); #endif // GPR_POSIX_ENV || GPR_LINUX_ENV if (restore_home_env) { SetOrUnsetEnv("HOME", home); @@ -1967,7 +1971,7 @@ TEST(CredentialsTest, TestChannelCredsDuplicateWithoutCallCreds) { RefCountedPtr dup = channel_creds->duplicate_without_call_credentials(); - GPR_ASSERT(dup == channel_creds); + CHECK(dup == channel_creds); dup.reset(); grpc_call_credentials* call_creds = @@ -1975,12 +1979,13 @@ TEST(CredentialsTest, TestChannelCredsDuplicateWithoutCallCreds) { grpc_channel_credentials* composite_creds = grpc_composite_channel_credentials_create(channel_creds, call_creds, nullptr); - GPR_ASSERT(strcmp(call_creds->debug_string().c_str(), - expected_creds_debug_string) == 0); + CHECK_EQ( + strcmp(call_creds->debug_string().c_str(), expected_creds_debug_string), + 0); call_creds->Unref(); dup = composite_creds->duplicate_without_call_credentials(); - GPR_ASSERT(dup == channel_creds); + CHECK(dup == channel_creds); dup.reset(); channel_creds->Unref(); @@ -2092,7 +2097,7 @@ TEST(CredentialsTest, TestAuthMetadataContext) { test_cases[i].desired_method_name, auth_md_context.method_name)); } - GPR_ASSERT(auth_md_context.channel_auth_context == nullptr); + CHECK_EQ(auth_md_context.channel_auth_context, nullptr); grpc_slice_unref(call_host); grpc_slice_unref(call_method); grpc_auth_metadata_context_reset(&auth_md_context); @@ -2103,14 +2108,14 @@ void validate_external_account_creds_token_exchage_request( const grpc_http_request* request, const char* host, const char* path, const char* body, size_t body_size, bool /*expect_actor_token*/) { // Check that the body is constructed properly. - GPR_ASSERT(body != nullptr); - GPR_ASSERT(body_size != 0); + CHECK_NE(body, nullptr); + CHECK_NE(body_size, 0); std::string get_url_equivalent = absl::StrFormat("%s?%s", "https://foo.com:5555/token", body); absl::StatusOr uri = URI::Parse(get_url_equivalent); if (!uri.ok()) { gpr_log(GPR_ERROR, "%s", uri.status().ToString().c_str()); - GPR_ASSERT(uri.ok()); + CHECK_OK(uri); } assert_query_parameters(*uri, "audience", "audience"); assert_query_parameters(*uri, "grant_type", @@ -2123,24 +2128,25 @@ void validate_external_account_creds_token_exchage_request( "https://www.googleapis.com/auth/cloud-platform"); // Check the rest of the request. - GPR_ASSERT(strcmp(host, "foo.com:5555") == 0); - GPR_ASSERT(strcmp(path, "/token") == 0); - GPR_ASSERT(request->hdr_count == 3); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Content-Type") == 0); - GPR_ASSERT( - strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded") == 0); - GPR_ASSERT(strcmp(request->hdrs[2].key, "Authorization") == 0); - GPR_ASSERT(strcmp(request->hdrs[2].value, - "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=") == 0); + CHECK_EQ(strcmp(host, "foo.com:5555"), 0); + CHECK_EQ(strcmp(path, "/token"), 0); + CHECK_EQ(request->hdr_count, 3); + CHECK_EQ(strcmp(request->hdrs[0].key, "Content-Type"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded"), + 0); + CHECK_EQ(strcmp(request->hdrs[2].key, "Authorization"), 0); + CHECK_EQ( + strcmp(request->hdrs[2].value, "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ="), + 0); } void validate_external_account_creds_token_exchage_request_with_url_encode( const grpc_http_request* request, const char* host, const char* path, const char* body, size_t body_size, bool /*expect_actor_token*/) { // Check that the body is constructed properly. - GPR_ASSERT(body != nullptr); - GPR_ASSERT(body_size != 0); - GPR_ASSERT( + CHECK_NE(body, nullptr); + CHECK_NE(body_size, 0); + CHECK_EQ( strcmp( std::string(body, body_size).c_str(), "audience=audience_!%40%23%24&grant_type=urn%3Aietf%3Aparams%3Aoauth%" @@ -2148,56 +2154,58 @@ void validate_external_account_creds_token_exchage_request_with_url_encode( "3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&subject_token_type=" "subject_token_type_!%40%23%24&subject_token=test_subject_token&" "scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform&" - "options=%7B%7D") == 0); + "options=%7B%7D"), + 0); // Check the rest of the request. - GPR_ASSERT(strcmp(host, "foo.com:5555") == 0); - GPR_ASSERT(strcmp(path, "/token_url_encode") == 0); - GPR_ASSERT(request->hdr_count == 3); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Content-Type") == 0); - GPR_ASSERT( - strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded") == 0); - GPR_ASSERT(strcmp(request->hdrs[2].key, "Authorization") == 0); - GPR_ASSERT(strcmp(request->hdrs[2].value, - "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=") == 0); + CHECK_EQ(strcmp(host, "foo.com:5555"), 0); + CHECK_EQ(strcmp(path, "/token_url_encode"), 0); + CHECK_EQ(request->hdr_count, 3); + CHECK_EQ(strcmp(request->hdrs[0].key, "Content-Type"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded"), + 0); + CHECK_EQ(strcmp(request->hdrs[2].key, "Authorization"), 0); + CHECK_EQ( + strcmp(request->hdrs[2].value, "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ="), + 0); } void validate_external_account_creds_service_account_impersonation_request( const grpc_http_request* request, const char* host, const char* path, const char* body, size_t body_size, bool /*expect_actor_token*/) { // Check that the body is constructed properly. - GPR_ASSERT(body != nullptr); - GPR_ASSERT(body_size != 0); - GPR_ASSERT(strcmp(body, "scope=scope_1%20scope_2&lifetime=3600s") == 0); + CHECK_NE(body, nullptr); + CHECK_NE(body_size, 0); + CHECK_EQ(strcmp(body, "scope=scope_1%20scope_2&lifetime=3600s"), 0); // Check the rest of the request. - GPR_ASSERT(strcmp(host, "foo.com:5555") == 0); - GPR_ASSERT(strcmp(path, "/service_account_impersonation") == 0); - GPR_ASSERT(request->hdr_count == 2); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Content-Type") == 0); - GPR_ASSERT( - strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded") == 0); - GPR_ASSERT(strcmp(request->hdrs[1].key, "Authorization") == 0); - GPR_ASSERT(strcmp(request->hdrs[1].value, - "Bearer token_exchange_access_token") == 0); + CHECK_EQ(strcmp(host, "foo.com:5555"), 0); + CHECK_EQ(strcmp(path, "/service_account_impersonation"), 0); + CHECK_EQ(request->hdr_count, 2); + CHECK_EQ(strcmp(request->hdrs[0].key, "Content-Type"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded"), + 0); + CHECK_EQ(strcmp(request->hdrs[1].key, "Authorization"), 0); + CHECK_EQ(strcmp(request->hdrs[1].value, "Bearer token_exchange_access_token"), + 0); } void validate_external_account_creds_serv_acc_imp_custom_lifetime_request( const grpc_http_request* request, const char* host, const char* path, const char* body, size_t body_size, bool /*expect_actor_token*/) { // Check that the body is constructed properly. - GPR_ASSERT(body != nullptr); - GPR_ASSERT(body_size != 0); - GPR_ASSERT(strcmp(body, "scope=scope_1%20scope_2&lifetime=1800s") == 0); + CHECK_NE(body, nullptr); + CHECK_NE(body_size, 0); + CHECK_EQ(strcmp(body, "scope=scope_1%20scope_2&lifetime=1800s"), 0); // Check the rest of the request. - GPR_ASSERT(strcmp(host, "foo.com:5555") == 0); - GPR_ASSERT(strcmp(path, "/service_account_impersonation") == 0); - GPR_ASSERT(request->hdr_count == 2); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Content-Type") == 0); - GPR_ASSERT( - strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded") == 0); - GPR_ASSERT(strcmp(request->hdrs[1].key, "Authorization") == 0); - GPR_ASSERT(strcmp(request->hdrs[1].value, - "Bearer token_exchange_access_token") == 0); + CHECK_EQ(strcmp(host, "foo.com:5555"), 0); + CHECK_EQ(strcmp(path, "/service_account_impersonation"), 0); + CHECK_EQ(request->hdr_count, 2); + CHECK_EQ(strcmp(request->hdrs[0].key, "Content-Type"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded"), + 0); + CHECK_EQ(strcmp(request->hdrs[1].key, "Authorization"), 0); + CHECK_EQ(strcmp(request->hdrs[1].value, "Bearer token_exchange_access_token"), + 0); } int external_acc_creds_serv_acc_imp_custom_lifetime_httpcli_post_success( @@ -2289,15 +2297,15 @@ void validate_aws_external_account_creds_token_exchage_request( const grpc_http_request* request, const char* host, const char* path, const char* body, size_t body_size, bool /*expect_actor_token*/) { // Check that the body is constructed properly. - GPR_ASSERT(body != nullptr); - GPR_ASSERT(body_size != 0); + CHECK_NE(body, nullptr); + CHECK_NE(body_size, 0); // Check that the regional_cred_verification_url got constructed // with the correct AWS Region ("test_regionz" or "test_region"). - GPR_ASSERT(strstr(body, "regional_cred_verification_url_test_region")); + CHECK(strstr(body, "regional_cred_verification_url_test_region")); std::string get_url_equivalent = absl::StrFormat("%s?%s", "https://foo.com:5555/token", body); absl::StatusOr uri = URI::Parse(get_url_equivalent); - GPR_ASSERT(uri.ok()); + CHECK_OK(uri); assert_query_parameters(*uri, "audience", "audience"); assert_query_parameters(*uri, "grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"); @@ -2307,21 +2315,22 @@ void validate_aws_external_account_creds_token_exchage_request( assert_query_parameters(*uri, "scope", "https://www.googleapis.com/auth/cloud-platform"); // Check the rest of the request. - GPR_ASSERT(strcmp(host, "foo.com:5555") == 0); - GPR_ASSERT(strcmp(path, "/token") == 0); - GPR_ASSERT(request->hdr_count == 3); - GPR_ASSERT(strcmp(request->hdrs[0].key, "Content-Type") == 0); - GPR_ASSERT( - strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded") == 0); - GPR_ASSERT(strcmp(request->hdrs[1].key, "x-goog-api-client") == 0); + CHECK_EQ(strcmp(host, "foo.com:5555"), 0); + CHECK_EQ(strcmp(path, "/token"), 0); + CHECK_EQ(request->hdr_count, 3); + CHECK_EQ(strcmp(request->hdrs[0].key, "Content-Type"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "application/x-www-form-urlencoded"), + 0); + CHECK_EQ(strcmp(request->hdrs[1].key, "x-goog-api-client"), 0); EXPECT_EQ( request->hdrs[1].value, absl::StrFormat("gl-cpp/unknown auth/%s google-byoid-sdk source/aws " "sa-impersonation/false config-lifetime/false", grpc_version_string())); - GPR_ASSERT(strcmp(request->hdrs[2].key, "Authorization") == 0); - GPR_ASSERT(strcmp(request->hdrs[2].value, - "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=") == 0); + CHECK_EQ(strcmp(request->hdrs[2].key, "Authorization"), 0); + CHECK_EQ( + strcmp(request->hdrs[2].value, "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ="), + 0); } int aws_external_account_creds_httpcli_get_success( @@ -2345,9 +2354,9 @@ int aws_external_account_creds_httpcli_get_success( int aws_imdsv2_external_account_creds_httpcli_get_success( const grpc_http_request* request, const char* host, const char* path, Timestamp deadline, grpc_closure* on_done, grpc_http_response* response) { - GPR_ASSERT(request->hdr_count == 1); - GPR_ASSERT(strcmp(request->hdrs[0].key, "x-aws-ec2-metadata-token") == 0); - GPR_ASSERT(strcmp(request->hdrs[0].value, aws_imdsv2_session_token) == 0); + CHECK_EQ(request->hdr_count, 1); + CHECK_EQ(strcmp(request->hdrs[0].key, "x-aws-ec2-metadata-token"), 0); + CHECK_EQ(strcmp(request->hdrs[0].value, aws_imdsv2_session_token), 0); return aws_external_account_creds_httpcli_get_success( request, host, path, deadline, on_done, response); } @@ -2356,11 +2365,11 @@ int aws_imdsv2_external_account_creds_httpcli_put_success( const grpc_http_request* request, const char* /*host*/, const char* path, const char* /*body*/, size_t /*body_size*/, Timestamp /*deadline*/, grpc_closure* on_done, grpc_http_response* response) { - GPR_ASSERT(request->hdr_count == 1); - GPR_ASSERT(strcmp(request->hdrs[0].key, - "x-aws-ec2-metadata-token-ttl-seconds") == 0); - GPR_ASSERT(strcmp(request->hdrs[0].value, "300") == 0); - GPR_ASSERT(strcmp(path, "/imdsv2_session_token_url") == 0); + CHECK_EQ(request->hdr_count, 1); + CHECK_EQ(strcmp(request->hdrs[0].key, "x-aws-ec2-metadata-token-ttl-seconds"), + 0); + CHECK_EQ(strcmp(request->hdrs[0].value, "300"), 0); + CHECK_EQ(strcmp(path, "/imdsv2_session_token_url"), 0); *response = http_response(200, aws_imdsv2_session_token); ExecCtx::Run(DEBUG_LOCATION, on_done, absl::OkStatus()); return 1; @@ -2506,7 +2515,7 @@ TEST(CredentialsTest, TestExternalAccountCredsSuccess) { }; TestExternalAccountCredentials creds(options, {}); // Check security level. - GPR_ASSERT(creds.min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds.min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); // First request: http put should be called. auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); @@ -2585,7 +2594,7 @@ TEST(CredentialsTest, }; TestExternalAccountCredentials creds(options, {"scope_1", "scope_2"}); // Check security level. - GPR_ASSERT(creds.min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds.min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); // First request: http put should be called. auto state = RequestMetadataState::NewInstance( absl::OkStatus(), @@ -2623,7 +2632,7 @@ TEST( }; TestExternalAccountCredentials creds(options, {"scope_1", "scope_2"}); // Check security level. - GPR_ASSERT(creds.min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK_EQ(creds.min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); // First request: http put should be called. auto state = RequestMetadataState::NewInstance( absl::OkStatus(), @@ -2657,12 +2666,12 @@ TEST( "\"client_id\":\"client_id\",\"client_secret\":\"client_secret\"}"; grpc_error_handle error1, error2; auto json1 = JsonParse(options_string1); - GPR_ASSERT(json1.ok()); + CHECK_OK(json1); ExternalAccountCredentials::Create(*json1, {"scope1", "scope2"}, &error1); std::string actual_error1, expected_error1 = "token_lifetime_seconds must be more than 600s"; grpc_error_get_str(error1, StatusStrProperty::kDescription, &actual_error1); - GPR_ASSERT(strcmp(actual_error1.c_str(), expected_error1.c_str()) == 0); + CHECK_EQ(strcmp(actual_error1.c_str(), expected_error1.c_str()), 0); const char* options_string2 = "{\"type\":\"external_account\",\"audience\":\"audience\"," @@ -2679,12 +2688,12 @@ TEST( "token\"}},\"quota_project_id\":\"quota_project_id\"," "\"client_id\":\"client_id\",\"client_secret\":\"client_secret\"}"; auto json2 = JsonParse(options_string2); - GPR_ASSERT(json2.ok()); + CHECK_OK(json2); ExternalAccountCredentials::Create(*json2, {"scope1", "scope2"}, &error2); std::string actual_error2, expected_error2 = "token_lifetime_seconds must be less than 43200s"; grpc_error_get_str(error2, StatusStrProperty::kDescription, &actual_error2); - GPR_ASSERT(strcmp(actual_error2.c_str(), expected_error2.c_str()) == 0); + CHECK_EQ(strcmp(actual_error2.c_str(), expected_error2.c_str()), 0); } TEST(CredentialsTest, TestExternalAccountCredsFailureInvalidTokenUrl) { @@ -2802,7 +2811,7 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatText) { ExecCtx exec_ctx; auto credential_source = JsonParse( valid_url_external_account_creds_options_credential_source_format_text); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -2822,9 +2831,9 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatText) { }; grpc_error_handle error; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(url_external_account_creds_httpcli_get_success, @@ -2843,7 +2852,7 @@ TEST(CredentialsTest, ExecCtx exec_ctx; auto credential_source = JsonParse( valid_url_external_account_creds_options_credential_source_with_qurey_params_format_text); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -2863,9 +2872,9 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(url_external_account_creds_httpcli_get_success, @@ -2881,7 +2890,7 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatJson) { ExecCtx exec_ctx; auto credential_source = JsonParse( valid_url_external_account_creds_options_credential_source_format_json); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -2901,9 +2910,9 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatJson) { }; grpc_error_handle error; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(url_external_account_creds_httpcli_get_success, @@ -2919,7 +2928,7 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsFailureInvalidCredentialSourceUrl) { auto credential_source = JsonParse(invalid_url_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -2939,11 +2948,11 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds == nullptr); + CHECK(creds == nullptr); std::string actual_error; - GPR_ASSERT(grpc_error_get_str(error, StatusStrProperty::kDescription, - &actual_error)); - GPR_ASSERT(absl::StartsWith(actual_error, "Invalid credential source url.")); + CHECK(grpc_error_get_str(error, StatusStrProperty::kDescription, + &actual_error)); + CHECK(absl::StartsWith(actual_error, "Invalid credential source url.")); } TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatText) { @@ -2952,7 +2961,7 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatText) { auto credential_source = JsonParse(absl::StrFormat( "{\"file\":\"%s\"}", absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}}))); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -2972,9 +2981,9 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatText) { }; grpc_error_handle error; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(httpcli_get_should_not_be_called, @@ -3001,7 +3010,7 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatJson) { "}\n" "}", absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}}))); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3021,9 +3030,9 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatJson) { }; grpc_error_handle error; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(httpcli_get_should_not_be_called, @@ -3039,7 +3048,7 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatJson) { TEST(CredentialsTest, TestFileExternalAccountCredsFailureFileNotFound) { ExecCtx exec_ctx; auto credential_source = JsonParse("{\"file\":\"non_exisiting_file\"}"); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3059,8 +3068,8 @@ TEST(CredentialsTest, TestFileExternalAccountCredsFailureFileNotFound) { }; grpc_error_handle error; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); + CHECK(creds != nullptr); + CHECK_OK(error); HttpRequest::SetOverride(httpcli_get_should_not_be_called, httpcli_post_should_not_be_called, httpcli_put_should_not_be_called); @@ -3087,7 +3096,7 @@ TEST(CredentialsTest, TestFileExternalAccountCredsFailureInvalidJsonContent) { "}\n" "}", absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}}))); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3107,8 +3116,8 @@ TEST(CredentialsTest, TestFileExternalAccountCredsFailureInvalidJsonContent) { }; grpc_error_handle error; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); + CHECK(creds != nullptr); + CHECK_OK(error); HttpRequest::SetOverride(httpcli_get_should_not_be_called, httpcli_post_should_not_be_called, httpcli_put_should_not_be_called); @@ -3128,7 +3137,7 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccess) { ExecCtx exec_ctx; auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3148,9 +3157,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccess) { }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3166,7 +3175,7 @@ TEST(CredentialsTest, TestAwsImdsv2ExternalAccountCredsSuccess) { ExecCtx exec_ctx; auto credential_source = JsonParse( valid_aws_imdsv2_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3186,9 +3195,9 @@ TEST(CredentialsTest, TestAwsImdsv2ExternalAccountCredsSuccess) { }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride( @@ -3210,7 +3219,7 @@ TEST(CredentialsTest, SetEnv("AWS_SESSION_TOKEN", "test_token"); auto credential_source = JsonParse( valid_aws_imdsv2_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3230,9 +3239,9 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3257,7 +3266,7 @@ TEST( SetEnv("AWS_SECRET_ACCESS_KEY", "test_secret_access_key"); auto credential_source = JsonParse( valid_aws_imdsv2_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3277,9 +3286,9 @@ TEST( }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3298,7 +3307,7 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessIpv6) { ExecCtx exec_ctx; auto credential_source = JsonParse( valid_aws_external_account_creds_options_credential_source_ipv6); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3318,9 +3327,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessIpv6) { }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride( @@ -3338,7 +3347,7 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysUrl) { SetEnv("AWS_REGION", "test_regionz"); auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3358,9 +3367,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysUrl) { }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3379,7 +3388,7 @@ TEST(CredentialsTest, SetEnv("AWS_DEFAULT_REGION", "test_regionz"); auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3399,9 +3408,9 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3422,7 +3431,7 @@ TEST(CredentialsTest, SetEnv("AWS_DEFAULT_REGION", "ERROR_REGION"); auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3442,9 +3451,9 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3465,7 +3474,7 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionUrlKeysEnv) { SetEnv("AWS_SESSION_TOKEN", "test_token"); auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3485,9 +3494,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionUrlKeysEnv) { }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3510,7 +3519,7 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysEnv) { SetEnv("AWS_SESSION_TOKEN", "test_token"); auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3530,9 +3539,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysEnv) { }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3559,7 +3568,7 @@ TEST(CredentialsTest, SetEnv("AWS_SESSION_TOKEN", "test_token"); auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3579,9 +3588,9 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3608,7 +3617,7 @@ TEST(CredentialsTest, SetEnv("AWS_SESSION_TOKEN", "test_token"); auto credential_source = JsonParse(valid_aws_external_account_creds_options_credential_source); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3628,9 +3637,9 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); auto state = RequestMetadataState::NewInstance( absl::OkStatus(), "authorization: Bearer token_exchange_access_token"); HttpRequest::SetOverride(aws_external_account_creds_httpcli_get_success, @@ -3664,7 +3673,7 @@ TEST(CredentialsTest, TestExternalAccountCredentialsCreateSuccess) { const char* url_scopes_string = "scope1,scope2"; grpc_call_credentials* url_creds = grpc_external_account_credentials_create( url_options_string, url_scopes_string); - GPR_ASSERT(url_creds != nullptr); + CHECK_NE(url_creds, nullptr); url_creds->Unref(); // file credentials const char* file_options_string = @@ -3680,7 +3689,7 @@ TEST(CredentialsTest, TestExternalAccountCredentialsCreateSuccess) { const char* file_scopes_string = "scope1,scope2"; grpc_call_credentials* file_creds = grpc_external_account_credentials_create( file_options_string, file_scopes_string); - GPR_ASSERT(file_creds != nullptr); + CHECK_NE(file_creds, nullptr); file_creds->Unref(); // aws credentials const char* aws_options_string = @@ -3700,7 +3709,7 @@ TEST(CredentialsTest, TestExternalAccountCredentialsCreateSuccess) { const char* aws_scopes_string = "scope1,scope2"; grpc_call_credentials* aws_creds = grpc_external_account_credentials_create( aws_options_string, aws_scopes_string); - GPR_ASSERT(aws_creds != nullptr); + CHECK_NE(aws_creds, nullptr); aws_creds->Unref(); } @@ -3708,7 +3717,7 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureUnmatchedEnvironmentId) { auto credential_source = JsonParse( invalid_aws_external_account_creds_options_credential_source_unmatched_environment_id); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3728,12 +3737,12 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds == nullptr); + CHECK(creds == nullptr); std::string expected_error = "environment_id does not match."; std::string actual_error; - GPR_ASSERT(grpc_error_get_str(error, StatusStrProperty::kDescription, - &actual_error)); - GPR_ASSERT(expected_error == actual_error); + CHECK(grpc_error_get_str(error, StatusStrProperty::kDescription, + &actual_error)); + CHECK(expected_error == actual_error); } TEST(CredentialsTest, @@ -3741,7 +3750,7 @@ TEST(CredentialsTest, ExecCtx exec_ctx; auto credential_source = JsonParse( invalid_aws_external_account_creds_options_credential_source_invalid_regional_cred_verification_url); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3761,9 +3770,9 @@ TEST(CredentialsTest, }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); error = GRPC_ERROR_CREATE("Creating aws request signer failed."); grpc_error_handle expected_error = GRPC_ERROR_CREATE_REFERENCING( "Error occurred when fetching oauth2 token.", &error, 1); @@ -3781,7 +3790,7 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureMissingRoleName) { ExecCtx exec_ctx; auto credential_source = JsonParse( invalid_aws_external_account_creds_options_credential_source_missing_role_name); - GPR_ASSERT(credential_source.ok()); + CHECK_OK(credential_source); TestExternalAccountCredentials::ServiceAccountImpersonation service_account_impersonation; service_account_impersonation.token_lifetime_seconds = 3600; @@ -3801,9 +3810,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureMissingRoleName) { }; grpc_error_handle error; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); - GPR_ASSERT(creds != nullptr); - GPR_ASSERT(error.ok()); - GPR_ASSERT(creds->min_security_level() == GRPC_PRIVACY_AND_INTEGRITY); + CHECK(creds != nullptr); + CHECK_OK(error); + CHECK_EQ(creds->min_security_level(), GRPC_PRIVACY_AND_INTEGRITY); error = GRPC_ERROR_CREATE("Missing role name when retrieving signing keys."); grpc_error_handle expected_error = GRPC_ERROR_CREATE_REFERENCING( "Error occurred when fetching oauth2 token.", &error, 1); @@ -3822,7 +3831,7 @@ TEST(CredentialsTest, const char* options_string = "invalid_json"; grpc_call_credentials* creds = grpc_external_account_credentials_create(options_string, ""); - GPR_ASSERT(creds == nullptr); + CHECK(creds == nullptr); } TEST(CredentialsTest, @@ -3830,7 +3839,7 @@ TEST(CredentialsTest, const char* options_string = "{\"random_key\":\"random_value\"}"; grpc_call_credentials* creds = grpc_external_account_credentials_create(options_string, ""); - GPR_ASSERT(creds == nullptr); + CHECK(creds == nullptr); } TEST( @@ -3848,7 +3857,7 @@ TEST( "secret\"}"; grpc_call_credentials* creds = grpc_external_account_credentials_create(options_string, ""); - GPR_ASSERT(creds == nullptr); + CHECK(creds == nullptr); } TEST(CredentialsTest, @@ -3870,7 +3879,7 @@ TEST(CredentialsTest, const char* url_scopes_string = "scope1,scope2"; grpc_call_credentials* url_creds = grpc_external_account_credentials_create( url_options_string, url_scopes_string); - GPR_ASSERT(url_creds != nullptr); + CHECK_NE(url_creds, nullptr); url_creds->Unref(); } @@ -3893,7 +3902,7 @@ TEST(CredentialsTest, const char* url_scopes_string = "scope1,scope2"; grpc_call_credentials* url_creds = grpc_external_account_credentials_create( url_options_string, url_scopes_string); - GPR_ASSERT(url_creds == nullptr); + CHECK_EQ(url_creds, nullptr); } TEST(CredentialsTest, TestInsecureCredentialsCompareSuccess) { @@ -3931,14 +3940,14 @@ TEST(CredentialsTest, TestInsecureCredentialsSingletonCreate) { TEST(CredentialsTest, TestFakeCallCredentialsCompareSuccess) { auto call_creds = MakeRefCounted(); - GPR_ASSERT(call_creds->cmp(call_creds.get()) == 0); + CHECK_EQ(call_creds->cmp(call_creds.get()), 0); } TEST(CredentialsTest, TestFakeCallCredentialsCompareFailure) { auto fake_creds = MakeRefCounted(); auto* md_creds = grpc_md_only_test_credentials_create("key", "value"); - GPR_ASSERT(fake_creds->cmp(md_creds) != 0); - GPR_ASSERT(md_creds->cmp(fake_creds.get()) != 0); + CHECK_NE(fake_creds->cmp(md_creds), 0); + CHECK_NE(md_creds->cmp(fake_creds.get()), 0); grpc_call_credentials_release(md_creds); } diff --git a/test/core/security/fetch_oauth2.cc b/test/core/security/fetch_oauth2.cc index 49cee158a09..c60c85bbf7f 100644 --- a/test/core/security/fetch_oauth2.cc +++ b/test/core/security/fetch_oauth2.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include diff --git a/test/core/security/grpc_tls_credentials_options_comparator_test.cc b/test/core/security/grpc_tls_credentials_options_comparator_test.cc index 6971f0c20e5..0f1e1e8c828 100644 --- a/test/core/security/grpc_tls_credentials_options_comparator_test.cc +++ b/test/core/security/grpc_tls_credentials_options_comparator_test.cc @@ -24,6 +24,8 @@ #include +#include + #include "src/core/lib/security/credentials/xds/xds_credentials.h" #include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h" #include "test/core/util/test_config.h" diff --git a/test/core/security/grpc_tls_credentials_options_test.cc b/test/core/security/grpc_tls_credentials_options_test.cc index 0b903ae0c05..f213e987c40 100644 --- a/test/core/security/grpc_tls_credentials_options_test.cc +++ b/test/core/security/grpc_tls_credentials_options_test.cc @@ -21,6 +21,7 @@ #include #include +#include #include #include #include diff --git a/test/core/security/json_token_test.cc b/test/core/security/json_token_test.cc index 5e89cf292aa..97cd240ee13 100644 --- a/test/core/security/json_token_test.cc +++ b/test/core/security/json_token_test.cc @@ -25,6 +25,7 @@ #include "absl/strings/escaping.h" +#include #include #include #include diff --git a/test/core/security/oauth2_utils.cc b/test/core/security/oauth2_utils.cc index 956783d2ff3..a23c7b4d5a1 100644 --- a/test/core/security/oauth2_utils.cc +++ b/test/core/security/oauth2_utils.cc @@ -20,6 +20,7 @@ #include +#include #include #include #include diff --git a/test/core/security/print_google_default_creds_token.cc b/test/core/security/print_google_default_creds_token.cc index a5ade93304c..66ea4a904c0 100644 --- a/test/core/security/print_google_default_creds_token.cc +++ b/test/core/security/print_google_default_creds_token.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include diff --git a/test/core/security/security_connector_test.cc b/test/core/security/security_connector_test.cc index cb781d1fd7e..83df36a3968 100644 --- a/test/core/security/security_connector_test.cc +++ b/test/core/security/security_connector_test.cc @@ -23,6 +23,7 @@ #include +#include #include #include #include diff --git a/test/core/security/ssl_server_fuzzer.cc b/test/core/security/ssl_server_fuzzer.cc index 4a8b5e47742..e657550f376 100644 --- a/test/core/security/ssl_server_fuzzer.cc +++ b/test/core/security/ssl_server_fuzzer.cc @@ -16,6 +16,7 @@ // // +#include #include #include #include diff --git a/test/core/security/tls_security_connector_test.cc b/test/core/security/tls_security_connector_test.cc index f1bcc410653..264eb8103db 100644 --- a/test/core/security/tls_security_connector_test.cc +++ b/test/core/security/tls_security_connector_test.cc @@ -24,6 +24,7 @@ #include #include +#include #include #include #include diff --git a/test/core/surface/channel_init_test.cc b/test/core/surface/channel_init_test.cc index cd7bfc7f347..4986cc3a839 100644 --- a/test/core/surface/channel_init_test.cc +++ b/test/core/surface/channel_init_test.cc @@ -15,6 +15,7 @@ #include "src/core/lib/surface/channel_init.h" #include +#include #include #include "absl/strings/string_view.h" @@ -206,9 +207,10 @@ class TestFilter1 { public: explicit TestFilter1(int* p) : p_(p) {} - static absl::StatusOr Create(const ChannelArgs& args, Empty) { + static absl::StatusOr> Create( + const ChannelArgs& args, Empty) { EXPECT_EQ(args.GetInt("foo"), 1); - return TestFilter1(args.GetPointer("p")); + return std::make_unique(args.GetPointer("p")); } static const grpc_channel_filter kFilter; diff --git a/test/core/surface/concurrent_connectivity_test.cc b/test/core/surface/concurrent_connectivity_test.cc index 2b1ee72dc94..3e73c423719 100644 --- a/test/core/surface/concurrent_connectivity_test.cc +++ b/test/core/surface/concurrent_connectivity_test.cc @@ -26,6 +26,7 @@ #include "absl/strings/str_cat.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/surface/num_external_connectivity_watchers_test.cc b/test/core/surface/num_external_connectivity_watchers_test.cc index 40ca9b67385..ec43da2fdad 100644 --- a/test/core/surface/num_external_connectivity_watchers_test.cc +++ b/test/core/surface/num_external_connectivity_watchers_test.cc @@ -22,6 +22,7 @@ #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/surface/sequential_connectivity_test.cc b/test/core/surface/sequential_connectivity_test.cc index 73a053e1196..17f93f194fa 100644 --- a/test/core/surface/sequential_connectivity_test.cc +++ b/test/core/surface/sequential_connectivity_test.cc @@ -24,6 +24,7 @@ #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/surface/server_chttp2_test.cc b/test/core/surface/server_chttp2_test.cc index 3c211a9dd81..3e04c59df8a 100644 --- a/test/core/surface/server_chttp2_test.cc +++ b/test/core/surface/server_chttp2_test.cc @@ -20,6 +20,7 @@ #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/surface/server_test.cc b/test/core/surface/server_test.cc index c3a927a9f8b..a111b836f0f 100644 --- a/test/core/surface/server_test.cc +++ b/test/core/surface/server_test.cc @@ -26,6 +26,7 @@ #include "absl/strings/str_cat.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/transport/chaotic_good/client_transport_error_test.cc b/test/core/transport/chaotic_good/client_transport_error_test.cc index 453e99a3663..bd1e1b77f7a 100644 --- a/test/core/transport/chaotic_good/client_transport_error_test.cc +++ b/test/core/transport/chaotic_good/client_transport_error_test.cc @@ -105,22 +105,21 @@ struct MockPromiseEndpoint { auto SendClientToServerMessages(CallInitiator initiator, int num_messages) { return Loop([initiator, num_messages]() mutable { bool has_message = (num_messages > 0); - return If( - has_message, - Seq(initiator.PushMessage(GetContext()->MakePooled()), - [&num_messages]() -> LoopCtl { - --num_messages; - return Continue(); - }), - [initiator]() mutable -> LoopCtl { - initiator.FinishSends(); - return absl::OkStatus(); - }); + return If(has_message, + Seq(initiator.PushMessage(Arena::MakePooled()), + [&num_messages]() -> LoopCtl { + --num_messages; + return Continue(); + }), + [initiator]() mutable -> LoopCtl { + initiator.FinishSends(); + return absl::OkStatus(); + }); }); } ClientMetadataHandle TestInitialMetadata() { - auto md = GetContext()->MakePooled(); + auto md = Arena::MakePooled(); md->Set(HttpPathMetadata(), Slice::FromStaticString("/test")); return md; } @@ -178,14 +177,13 @@ TEST_F(ClientTransportTest, AddOneStreamWithWriteFailed) { std::move(control_endpoint.promise_endpoint), std::move(data_endpoint.promise_endpoint), MakeChannelArgs(), event_engine(), HPackParser(), HPackCompressor()); - auto call = - MakeCall(event_engine().get(), Arena::Create(8192, memory_allocator())); - transport->StartCall(std::move(call.handler)); - call.initiator.SpawnGuarded("test-send", [initiator = - call.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 1)); - }); + auto call = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(8192, memory_allocator()), true); + transport->StartCall(call.handler.V2HackToStartCallWithoutACallFilterStack()); + call.initiator.SpawnGuarded("test-send", + [initiator = call.initiator]() mutable { + return SendClientToServerMessages(initiator, 1); + }); StrictMock> on_done; EXPECT_CALL(on_done, Call()); call.initiator.SpawnInfallible( @@ -193,7 +191,7 @@ TEST_F(ClientTransportTest, AddOneStreamWithWriteFailed) { return Seq( initiator.PullServerInitialMetadata(), [](ValueOrFailure> md) { - EXPECT_FALSE(md.ok()); + EXPECT_TRUE(md.ok()); return Empty{}; }, initiator.PullServerTrailingMetadata(), @@ -224,14 +222,13 @@ TEST_F(ClientTransportTest, AddOneStreamWithReadFailed) { std::move(control_endpoint.promise_endpoint), std::move(data_endpoint.promise_endpoint), MakeChannelArgs(), event_engine(), HPackParser(), HPackCompressor()); - auto call = - MakeCall(event_engine().get(), Arena::Create(8192, memory_allocator())); - transport->StartCall(std::move(call.handler)); - call.initiator.SpawnGuarded("test-send", [initiator = - call.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 1)); - }); + auto call = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(8192, memory_allocator()), true); + transport->StartCall(call.handler.V2HackToStartCallWithoutACallFilterStack()); + call.initiator.SpawnGuarded("test-send", + [initiator = call.initiator]() mutable { + return SendClientToServerMessages(initiator, 1); + }); StrictMock> on_done; EXPECT_CALL(on_done, Call()); call.initiator.SpawnInfallible( @@ -239,7 +236,7 @@ TEST_F(ClientTransportTest, AddOneStreamWithReadFailed) { return Seq( initiator.PullServerInitialMetadata(), [](ValueOrFailure> md) { - EXPECT_FALSE(md.ok()); + EXPECT_TRUE(md.ok()); return Empty{}; }, initiator.PullServerTrailingMetadata(), @@ -278,22 +275,22 @@ TEST_F(ClientTransportTest, AddMultipleStreamWithWriteFailed) { std::move(control_endpoint.promise_endpoint), std::move(data_endpoint.promise_endpoint), MakeChannelArgs(), event_engine(), HPackParser(), HPackCompressor()); - auto call1 = - MakeCall(event_engine().get(), Arena::Create(8192, memory_allocator())); - transport->StartCall(std::move(call1.handler)); - auto call2 = - MakeCall(event_engine().get(), Arena::Create(8192, memory_allocator())); - transport->StartCall(std::move(call2.handler)); - call1.initiator.SpawnGuarded("test-send-1", [initiator = - call1.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 1)); - }); - call2.initiator.SpawnGuarded("test-send-2", [initiator = - call2.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 1)); - }); + auto call1 = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(8192, memory_allocator()), true); + transport->StartCall( + call1.handler.V2HackToStartCallWithoutACallFilterStack()); + auto call2 = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(8192, memory_allocator()), true); + transport->StartCall( + call2.handler.V2HackToStartCallWithoutACallFilterStack()); + call1.initiator.SpawnGuarded( + "test-send-1", [initiator = call1.initiator]() mutable { + return SendClientToServerMessages(initiator, 1); + }); + call2.initiator.SpawnGuarded( + "test-send-2", [initiator = call2.initiator]() mutable { + return SendClientToServerMessages(initiator, 1); + }); StrictMock> on_done1; EXPECT_CALL(on_done1, Call()); StrictMock> on_done2; @@ -303,7 +300,7 @@ TEST_F(ClientTransportTest, AddMultipleStreamWithWriteFailed) { return Seq( initiator.PullServerInitialMetadata(), [](ValueOrFailure> md) { - EXPECT_FALSE(md.ok()); + EXPECT_TRUE(md.ok()); return Empty{}; }, initiator.PullServerTrailingMetadata(), @@ -319,7 +316,7 @@ TEST_F(ClientTransportTest, AddMultipleStreamWithWriteFailed) { return Seq( initiator.PullServerInitialMetadata(), [](ValueOrFailure> md) { - EXPECT_FALSE(md.ok()); + EXPECT_TRUE(md.ok()); return Empty{}; }, initiator.PullServerTrailingMetadata(), @@ -350,22 +347,22 @@ TEST_F(ClientTransportTest, AddMultipleStreamWithReadFailed) { std::move(control_endpoint.promise_endpoint), std::move(data_endpoint.promise_endpoint), MakeChannelArgs(), event_engine(), HPackParser(), HPackCompressor()); - auto call1 = - MakeCall(event_engine().get(), Arena::Create(8192, memory_allocator())); - transport->StartCall(std::move(call1.handler)); - auto call2 = - MakeCall(event_engine().get(), Arena::Create(8192, memory_allocator())); - transport->StartCall(std::move(call2.handler)); - call1.initiator.SpawnGuarded("test-send", [initiator = - call1.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 1)); - }); - call2.initiator.SpawnGuarded("test-send", [initiator = - call2.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 1)); - }); + auto call1 = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(8192, memory_allocator()), true); + transport->StartCall( + call1.handler.V2HackToStartCallWithoutACallFilterStack()); + auto call2 = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(8192, memory_allocator()), true); + transport->StartCall( + call2.handler.V2HackToStartCallWithoutACallFilterStack()); + call1.initiator.SpawnGuarded( + "test-send", [initiator = call1.initiator]() mutable { + return SendClientToServerMessages(initiator, 1); + }); + call2.initiator.SpawnGuarded( + "test-send", [initiator = call2.initiator]() mutable { + return SendClientToServerMessages(initiator, 1); + }); StrictMock> on_done1; EXPECT_CALL(on_done1, Call()); StrictMock> on_done2; @@ -375,7 +372,7 @@ TEST_F(ClientTransportTest, AddMultipleStreamWithReadFailed) { return Seq( initiator.PullServerInitialMetadata(), [](ValueOrFailure> md) { - EXPECT_FALSE(md.ok()); + EXPECT_TRUE(md.ok()); return Empty{}; }, initiator.PullServerTrailingMetadata(), @@ -391,7 +388,7 @@ TEST_F(ClientTransportTest, AddMultipleStreamWithReadFailed) { return Seq( initiator.PullServerInitialMetadata(), [](ValueOrFailure> md) { - EXPECT_FALSE(md.ok()); + EXPECT_TRUE(md.ok()); return Empty{}; }, initiator.PullServerTrailingMetadata(), diff --git a/test/core/transport/chaotic_good/client_transport_test.cc b/test/core/transport/chaotic_good/client_transport_test.cc index 387e483fc21..3acd0c0c273 100644 --- a/test/core/transport/chaotic_good/client_transport_test.cc +++ b/test/core/transport/chaotic_good/client_transport_test.cc @@ -67,7 +67,7 @@ const uint8_t kGrpcStatus0[] = {0x10, 0x0b, 0x67, 0x72, 0x70, 0x63, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x01, 0x30}; ClientMetadataHandle TestInitialMetadata() { - auto md = GetContext()->MakePooled(); + auto md = Arena::MakePooled(); md->Set(HttpPathMetadata(), Slice::FromStaticString("/demo.Service/Step")); return md; } @@ -78,7 +78,7 @@ auto SendClientToServerMessages(CallInitiator initiator, int num_messages) { bool has_message = (i < num_messages); return If( has_message, - Seq(initiator.PushMessage(GetContext()->MakePooled( + Seq(initiator.PushMessage(Arena::MakePooled( SliceBuffer(Slice::FromCopiedString(std::to_string(i))), 0)), [&i]() -> LoopCtl { ++i; @@ -115,9 +115,9 @@ TEST_F(TransportTest, AddOneStream) { std::move(control_endpoint.promise_endpoint), std::move(data_endpoint.promise_endpoint), MakeChannelArgs(), event_engine(), HPackParser(), HPackCompressor()); - auto call = - MakeCall(event_engine().get(), Arena::Create(1024, memory_allocator())); - transport->StartCall(std::move(call.handler)); + auto call = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(1024, memory_allocator()), true); + transport->StartCall(call.handler.V2HackToStartCallWithoutACallFilterStack()); StrictMock> on_done; EXPECT_CALL(on_done, Call()); control_endpoint.ExpectWrite( @@ -133,11 +133,10 @@ TEST_F(TransportTest, AddOneStream) { {EventEngineSlice::FromCopiedString("0"), Zeros(63)}, nullptr); control_endpoint.ExpectWrite( {SerializedFrameHeader(FrameType::kFragment, 4, 1, 0, 0, 0, 0)}, nullptr); - call.initiator.SpawnGuarded("test-send", [initiator = - call.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 1)); - }); + call.initiator.SpawnGuarded("test-send", + [initiator = call.initiator]() mutable { + return SendClientToServerMessages(initiator, 1); + }); call.initiator.SpawnInfallible( "test-read", [&on_done, initiator = call.initiator]() mutable { return Seq( @@ -152,18 +151,23 @@ TEST_F(TransportTest, AddOneStream) { "/demo.Service/Step"); return Empty{}; }, - initiator.PullMessage(), - [](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "12345678"); + [initiator]() mutable { return initiator.PullMessage(); }, + [](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "12345678"); return Empty{}; }, - initiator.PullMessage(), - [](NextResult msg) { - EXPECT_FALSE(msg.has_value()); + [initiator]() mutable { return initiator.PullMessage(); }, + [](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return Empty{}; }, - initiator.PullServerTrailingMetadata(), + [initiator]() mutable { + return initiator.PullServerTrailingMetadata(); + }, [&on_done](ServerMetadataHandle md) { EXPECT_EQ(md->get(GrpcStatusMetadata()).value(), GRPC_STATUS_OK); on_done.Call(); @@ -198,9 +202,9 @@ TEST_F(TransportTest, AddOneStreamMultipleMessages) { std::move(control_endpoint.promise_endpoint), std::move(data_endpoint.promise_endpoint), MakeChannelArgs(), event_engine(), HPackParser(), HPackCompressor()); - auto call = - MakeCall(event_engine().get(), Arena::Create(8192, memory_allocator())); - transport->StartCall(std::move(call.handler)); + auto call = MakeCall(TestInitialMetadata(), event_engine().get(), + Arena::Create(8192, memory_allocator()), true); + transport->StartCall(call.handler.V2HackToStartCallWithoutACallFilterStack()); StrictMock> on_done; EXPECT_CALL(on_done, Call()); control_endpoint.ExpectWrite( @@ -221,11 +225,10 @@ TEST_F(TransportTest, AddOneStreamMultipleMessages) { {EventEngineSlice::FromCopiedString("1"), Zeros(63)}, nullptr); control_endpoint.ExpectWrite( {SerializedFrameHeader(FrameType::kFragment, 4, 1, 0, 0, 0, 0)}, nullptr); - call.initiator.SpawnGuarded("test-send", [initiator = - call.initiator]() mutable { - return TrySeq(initiator.PushClientInitialMetadata(TestInitialMetadata()), - SendClientToServerMessages(initiator, 2)); - }); + call.initiator.SpawnGuarded("test-send", + [initiator = call.initiator]() mutable { + return SendClientToServerMessages(initiator, 2); + }); call.initiator.SpawnInfallible( "test-read", [&on_done, initiator = call.initiator]() mutable { return Seq( @@ -241,20 +244,25 @@ TEST_F(TransportTest, AddOneStreamMultipleMessages) { return Empty{}; }, initiator.PullMessage(), - [](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "12345678"); + [](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "12345678"); return Empty{}; }, initiator.PullMessage(), - [](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "87654321"); + [](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "87654321"); return Empty{}; }, initiator.PullMessage(), - [](NextResult msg) { - EXPECT_FALSE(msg.has_value()); + [](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return Empty{}; }, initiator.PullServerTrailingMetadata(), diff --git a/test/core/transport/chaotic_good/server_transport_test.cc b/test/core/transport/chaotic_good/server_transport_test.cc index 7c21a07c72d..a4e0272b87c 100644 --- a/test/core/transport/chaotic_good/server_transport_test.cc +++ b/test/core/transport/chaotic_good/server_transport_test.cc @@ -71,13 +71,13 @@ const uint8_t kGrpcStatus0[] = {0x40, 0x0b, 0x67, 0x72, 0x70, 0x63, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x01, 0x30}; ServerMetadataHandle TestInitialMetadata() { - auto md = GetContext()->MakePooled(); + auto md = Arena::MakePooled(); md->Set(HttpPathMetadata(), Slice::FromStaticString("/demo.Service/Step")); return md; } ServerMetadataHandle TestTrailingMetadata() { - auto md = GetContext()->MakePooled(); + auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_OK); return md; } @@ -87,7 +87,7 @@ class MockAcceptor : public ServerTransport::Acceptor { virtual ~MockAcceptor() = default; MOCK_METHOD(Arena*, CreateArena, (), (override)); MOCK_METHOD(absl::StatusOr, CreateCall, - (ClientMetadata & client_initial_metadata, Arena* arena), + (ClientMetadataHandle client_initial_metadata, Arena* arena), (override)); }; @@ -113,18 +113,59 @@ TEST_F(TransportTest, ReadAndWriteOneMessage) { {EventEngineSlice::FromCopiedString("12345678"), Zeros(56)}, nullptr); // Once that's read we'll create a new call auto* call_arena = Arena::Create(1024, memory_allocator()); - CallInitiatorAndHandler call = MakeCall(event_engine().get(), call_arena); EXPECT_CALL(acceptor, CreateArena).WillOnce(Return(call_arena)); + StrictMock> on_done; EXPECT_CALL(acceptor, CreateCall(_, call_arena)) - .WillOnce(WithArgs<0>([call_initiator = std::move(call.initiator)]( - ClientMetadata& client_initial_metadata) { - EXPECT_EQ(client_initial_metadata.get_pointer(HttpPathMetadata()) + .WillOnce(WithArgs<0>([this, call_arena, &on_done]( + ClientMetadataHandle client_initial_metadata) { + EXPECT_EQ(client_initial_metadata->get_pointer(HttpPathMetadata()) ->as_string_view(), "/demo.Service/Step"); - return call_initiator; + CallInitiatorAndHandler call = + MakeCall(std::move(client_initial_metadata), event_engine().get(), + call_arena, true); + auto handler = call.handler.V2HackToStartCallWithoutACallFilterStack(); + handler.SpawnInfallible("test-io", [&on_done, handler]() mutable { + return Seq( + handler.PullClientInitialMetadata(), + [](ValueOrFailure md) { + EXPECT_TRUE(md.ok()); + EXPECT_EQ(md.value() + ->get_pointer(HttpPathMetadata()) + ->as_string_view(), + "/demo.Service/Step"); + return Empty{}; + }, + [handler]() mutable { return handler.PullMessage(); }, + [](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "12345678"); + return Empty{}; + }, + [handler]() mutable { return handler.PullMessage(); }, + [](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); + return Empty{}; + }, + [handler]() mutable { + return handler.PushServerInitialMetadata(TestInitialMetadata()); + }, + [handler]() mutable { + return handler.PushMessage(Arena::MakePooled( + SliceBuffer(Slice::FromCopiedString("87654321")), 0)); + }, + [handler, &on_done]() mutable { + handler.PushServerTrailingMetadata(TestTrailingMetadata()); + on_done.Call(); + return Empty{}; + }); + }); + return std::move(call.initiator); })); transport->SetAcceptor(&acceptor); - StrictMock> on_done; EXPECT_CALL(on_done, Call()); EXPECT_CALL(*control_endpoint.endpoint, Read) .InSequence(control_endpoint.read_sequence) @@ -145,39 +186,6 @@ TEST_F(TransportTest, ReadAndWriteOneMessage) { sizeof(kGrpcStatus0)), EventEngineSlice::FromCopiedBuffer(kGrpcStatus0, sizeof(kGrpcStatus0))}, nullptr); - call.handler.SpawnInfallible( - "test-io", [&on_done, handler = call.handler]() mutable { - return Seq( - handler.PullClientInitialMetadata(), - [](ValueOrFailure md) { - EXPECT_TRUE(md.ok()); - EXPECT_EQ( - md.value()->get_pointer(HttpPathMetadata())->as_string_view(), - "/demo.Service/Step"); - return Empty{}; - }, - handler.PullMessage(), - [](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "12345678"); - return Empty{}; - }, - handler.PullMessage(), - [](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - return Empty{}; - }, - handler.PushServerInitialMetadata(TestInitialMetadata()), - handler.PushMessage(Arena::MakePooled( - SliceBuffer(Slice::FromCopiedString("87654321")), 0)), - [handler]() mutable { - return handler.PushServerTrailingMetadata(TestTrailingMetadata()); - }, - [&on_done]() mutable { - on_done.Call(); - return Empty{}; - }); - }); // Wait until ClientTransport's internal activities to finish. event_engine()->TickUntilIdle(); event_engine()->UnsetGlobalHooks(); diff --git a/test/core/transport/chttp2/remove_stream_from_stalled_lists_test.cc b/test/core/transport/chttp2/remove_stream_from_stalled_lists_test.cc index 0852008863b..3cdb2d9940f 100644 --- a/test/core/transport/chttp2/remove_stream_from_stalled_lists_test.cc +++ b/test/core/transport/chttp2/remove_stream_from_stalled_lists_test.cc @@ -31,6 +31,7 @@ #include "absl/types/optional.h" #include +#include #include #include #include diff --git a/test/core/transport/chttp2/settings_timeout_test.cc b/test/core/transport/chttp2/settings_timeout_test.cc index 61a45e0790e..7977929d083 100644 --- a/test/core/transport/chttp2/settings_timeout_test.cc +++ b/test/core/transport/chttp2/settings_timeout_test.cc @@ -30,6 +30,7 @@ #include "absl/strings/str_cat.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/transport/chttp2/stream_leak_with_queued_flow_control_update_test.cc b/test/core/transport/chttp2/stream_leak_with_queued_flow_control_update_test.cc index ef8aacabc36..423ed40e584 100644 --- a/test/core/transport/chttp2/stream_leak_with_queued_flow_control_update_test.cc +++ b/test/core/transport/chttp2/stream_leak_with_queued_flow_control_update_test.cc @@ -23,6 +23,7 @@ #include "gtest/gtest.h" #include +#include #include #include #include diff --git a/test/core/transport/chttp2/streams_not_seen_test.cc b/test/core/transport/chttp2/streams_not_seen_test.cc index 7105ec9b912..fe1626d48f4 100644 --- a/test/core/transport/chttp2/streams_not_seen_test.cc +++ b/test/core/transport/chttp2/streams_not_seen_test.cc @@ -38,6 +38,7 @@ #include "absl/types/optional.h" #include "gtest/gtest.h" +#include #include #include #include diff --git a/test/core/transport/chttp2/too_many_pings_test.cc b/test/core/transport/chttp2/too_many_pings_test.cc index cfb2ca8f1e6..474e2edb4b3 100644 --- a/test/core/transport/chttp2/too_many_pings_test.cc +++ b/test/core/transport/chttp2/too_many_pings_test.cc @@ -32,6 +32,7 @@ #include "gtest/gtest.h" #include +#include #include #include #include diff --git a/test/core/transport/test_suite/call_content.cc b/test/core/transport/test_suite/call_content.cc index cea4c5a0aa5..9e334f24fb6 100644 --- a/test/core/transport/test_suite/call_content.cc +++ b/test/core/transport/test_suite/call_content.cc @@ -63,21 +63,17 @@ void FillMetadata(const std::vector>& md, TRANSPORT_TEST(UnaryWithSomeContent) { SetServerAcceptor(); - auto initiator = CreateCall(); const auto client_initial_metadata = RandomMetadata(); const auto server_initial_metadata = RandomMetadata(); const auto server_trailing_metadata = RandomMetadata(); const auto client_payload = RandomMessage(); const auto server_payload = RandomMessage(); + auto md = Arena::MakePooled(); + FillMetadata(client_initial_metadata, *md); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - FillMetadata(client_initial_metadata, *md); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); + [&]() mutable { return initiator.PushMessage(Arena::MakePooled( SliceBuffer(Slice::FromCopiedString(client_payload)), 0)); }, @@ -93,14 +89,16 @@ TRANSPORT_TEST(UnaryWithSomeContent) { UnorderedElementsAreArray(server_initial_metadata)); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), server_payload); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + server_payload); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return initiator.PullServerTrailingMetadata(); }, [&](ValueOrFailure md) { @@ -118,14 +116,16 @@ TRANSPORT_TEST(UnaryWithSomeContent) { UnorderedElementsAreArray(client_initial_metadata)); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), client_payload); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + client_payload); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); auto md = Arena::MakePooled(); FillMetadata(server_initial_metadata, *md); return handler.PushServerInitialMetadata(std::move(md)); @@ -139,10 +139,7 @@ TRANSPORT_TEST(UnaryWithSomeContent) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); FillMetadata(server_trailing_metadata, *md); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); diff --git a/test/core/transport/test_suite/call_shapes.cc b/test/core/transport/test_suite/call_shapes.cc index acfa0ffb741..fdae653119d 100644 --- a/test/core/transport/test_suite/call_shapes.cc +++ b/test/core/transport/test_suite/call_shapes.cc @@ -18,16 +18,12 @@ namespace grpc_core { TRANSPORT_TEST(MetadataOnlyRequest) { SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); + [&]() mutable { initiator.FinishSends(); return initiator.PullServerInitialMetadata(); }, @@ -53,8 +49,9 @@ TRANSPORT_TEST(MetadataOnlyRequest) { "/foo/bar"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); auto md = Arena::MakePooled(); md->Set(ContentTypeMetadata(), ContentTypeMetadata::kApplicationGrpc); return handler.PushServerInitialMetadata(std::move(md)); @@ -63,10 +60,7 @@ TRANSPORT_TEST(MetadataOnlyRequest) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); @@ -79,16 +73,12 @@ TRANSPORT_TEST(MetadataOnlyRequestServerAbortsAfterInitialMetadata) { "rolling out soon, so leaving this disabled."; SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); + [&]() mutable { // We don't close the sending stream here. return initiator.PullServerInitialMetadata(); }, @@ -123,10 +113,7 @@ TRANSPORT_TEST(MetadataOnlyRequestServerAbortsAfterInitialMetadata) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); @@ -139,16 +126,12 @@ TRANSPORT_TEST(MetadataOnlyRequestServerAbortsImmediately) { "rolling out soon, so leaving this disabled."; SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); + [&]() mutable { // We don't close the sending stream here. return initiator.PullServerInitialMetadata(); }, @@ -175,10 +158,7 @@ TRANSPORT_TEST(MetadataOnlyRequestServerAbortsImmediately) { // and don't send initial metadata - just trailing metadata. auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); @@ -186,18 +166,9 @@ TRANSPORT_TEST(MetadataOnlyRequestServerAbortsImmediately) { TRANSPORT_TEST(CanCreateCallThenAbandonIt) { SetServerAcceptor(); - auto initiator = CreateCall(); - SpawnTestSeq( - initiator, "start-call", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); - return Empty{}; - }); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); auto handler = TickUntilServerCall(); SpawnTestSeq(initiator, "end-call", [&]() { initiator.Cancel(); @@ -208,16 +179,12 @@ TRANSPORT_TEST(CanCreateCallThenAbandonIt) { TRANSPORT_TEST(UnaryRequest) { SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); + [&]() mutable { return initiator.PushMessage(Arena::MakePooled( SliceBuffer(Slice::FromCopiedString("hello world")), 0)); }, @@ -233,15 +200,16 @@ TRANSPORT_TEST(UnaryRequest) { ContentTypeMetadata::kApplicationGrpc); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return initiator.PullServerTrailingMetadata(); }, [&](ValueOrFailure md) { @@ -259,14 +227,16 @@ TRANSPORT_TEST(UnaryRequest) { "/foo/bar"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); auto md = Arena::MakePooled(); md->Set(ContentTypeMetadata(), ContentTypeMetadata::kApplicationGrpc); return handler.PushServerInitialMetadata(std::move(md)); @@ -280,10 +250,7 @@ TRANSPORT_TEST(UnaryRequest) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); @@ -291,16 +258,12 @@ TRANSPORT_TEST(UnaryRequest) { TRANSPORT_TEST(UnaryRequestOmitCheckEndOfStream) { SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); + [&]() mutable { return initiator.PushMessage(Arena::MakePooled( SliceBuffer(Slice::FromCopiedString("hello world")), 0)); }, @@ -316,9 +279,10 @@ TRANSPORT_TEST(UnaryRequestOmitCheckEndOfStream) { ContentTypeMetadata::kApplicationGrpc); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor"); return initiator.PullServerTrailingMetadata(); }, @@ -337,9 +301,11 @@ TRANSPORT_TEST(UnaryRequestOmitCheckEndOfStream) { "/foo/bar"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world"); auto md = Arena::MakePooled(); md->Set(ContentTypeMetadata(), ContentTypeMetadata::kApplicationGrpc); return handler.PushServerInitialMetadata(std::move(md)); @@ -353,10 +319,7 @@ TRANSPORT_TEST(UnaryRequestOmitCheckEndOfStream) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); @@ -364,18 +327,12 @@ TRANSPORT_TEST(UnaryRequestOmitCheckEndOfStream) { TRANSPORT_TEST(UnaryRequestWaitForServerInitialMetadataBeforeSendingPayload) { SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); - return initiator.PullServerInitialMetadata(); - }, + [&]() mutable { return initiator.PullServerInitialMetadata(); }, [&](ValueOrFailure> md) { EXPECT_TRUE(md.ok()); EXPECT_TRUE(md.value().has_value()); @@ -389,15 +346,16 @@ TRANSPORT_TEST(UnaryRequestWaitForServerInitialMetadataBeforeSendingPayload) { initiator.FinishSends(); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return initiator.PullServerTrailingMetadata(); }, [&](ValueOrFailure md) { @@ -422,14 +380,16 @@ TRANSPORT_TEST(UnaryRequestWaitForServerInitialMetadataBeforeSendingPayload) { EXPECT_TRUE(result.ok()); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return handler.PushMessage(Arena::MakePooled( SliceBuffer(Slice::FromCopiedString("why hello neighbor")), 0)); }, @@ -437,10 +397,7 @@ TRANSPORT_TEST(UnaryRequestWaitForServerInitialMetadataBeforeSendingPayload) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); @@ -448,18 +405,12 @@ TRANSPORT_TEST(UnaryRequestWaitForServerInitialMetadataBeforeSendingPayload) { TRANSPORT_TEST(ClientStreamingRequest) { SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); - return initiator.PullServerInitialMetadata(); - }, + [&]() mutable { return initiator.PullServerInitialMetadata(); }, [&](ValueOrFailure> md) { EXPECT_TRUE(md.ok()); EXPECT_TRUE(md.value().has_value()); @@ -493,9 +444,9 @@ TRANSPORT_TEST(ClientStreamingRequest) { initiator.FinishSends(); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return initiator.PullServerTrailingMetadata(); }, [&](ValueOrFailure md) { @@ -520,40 +471,47 @@ TRANSPORT_TEST(ClientStreamingRequest) { EXPECT_TRUE(result.ok()); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world (2)"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world (2)"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world (3)"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world (3)"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world (4)"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world (4)"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), "hello world (5)"); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), + "hello world (5)"); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); @@ -561,18 +519,12 @@ TRANSPORT_TEST(ClientStreamingRequest) { TRANSPORT_TEST(ServerStreamingRequest) { SetServerAcceptor(); - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); + auto initiator = CreateCall(std::move(md)); SpawnTestSeq( initiator, "initiator", - [&]() { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), Slice::FromExternalString("/foo/bar")); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [&](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); - return initiator.PullServerInitialMetadata(); - }, + [&]() mutable { return initiator.PullServerInitialMetadata(); }, [&](ValueOrFailure> md) { EXPECT_TRUE(md.ok()); EXPECT_TRUE(md.value().has_value()); @@ -581,45 +533,51 @@ TRANSPORT_TEST(ServerStreamingRequest) { initiator.FinishSends(); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor (2)"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor (3)"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor (4)"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor (5)"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), "why hello neighbor (6)"); return initiator.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return initiator.PullServerTrailingMetadata(); }, [&](ValueOrFailure md) { @@ -644,9 +602,9 @@ TRANSPORT_TEST(ServerStreamingRequest) { EXPECT_TRUE(result.ok()); return handler.PullMessage(); }, - [&](NextResult msg) { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [&](ValueOrFailure> msg) { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return handler.PushMessage(Arena::MakePooled( SliceBuffer(Slice::FromCopiedString("why hello neighbor")), 0)); }, @@ -679,10 +637,7 @@ TRANSPORT_TEST(ServerStreamingRequest) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [&](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); WaitForAllPendingWork(); diff --git a/test/core/transport/test_suite/stress.cc b/test/core/transport/test_suite/stress.cc index 54e34ba98d5..ca20fb7ff3f 100644 --- a/test/core/transport/test_suite/stress.cc +++ b/test/core/transport/test_suite/stress.cc @@ -30,19 +30,14 @@ TRANSPORT_TEST(ManyUnaryRequests) { std::map client_messages; std::map server_messages; for (int i = 0; i < kNumRequests; i++) { - auto initiator = CreateCall(); + auto md = Arena::MakePooled(); + md->Set(HttpPathMetadata(), Slice::FromCopiedString(std::to_string(i))); + auto initiator = CreateCall(std::move(md)); client_messages[i] = RandomMessage(); server_messages[i] = RandomMessage(); SpawnTestSeq( initiator, make_call_name(i, "initiator"), - [initiator, i]() mutable { - auto md = Arena::MakePooled(); - md->Set(HttpPathMetadata(), - Slice::FromCopiedString(std::to_string(i))); - return initiator.PushClientInitialMetadata(std::move(md)); - }, - [initiator, i, &client_messages](StatusFlag status) mutable { - EXPECT_TRUE(status.ok()); + [initiator, i, &client_messages]() mutable { return initiator.PushMessage(Arena::MakePooled( SliceBuffer(Slice::FromCopiedString(client_messages[i])), 0)); }, @@ -59,16 +54,17 @@ TRANSPORT_TEST(ManyUnaryRequests) { ContentTypeMetadata::kApplicationGrpc); return initiator.PullMessage(); }, - [initiator, i, - &server_messages](NextResult msg) mutable { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [initiator, i, &server_messages]( + ValueOrFailure> msg) mutable { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), server_messages[i]); return initiator.PullMessage(); }, - [initiator](NextResult msg) mutable { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [initiator](ValueOrFailure> msg) mutable { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); return initiator.PullServerTrailingMetadata(); }, [initiator](ValueOrFailure md) mutable { @@ -92,16 +88,17 @@ TRANSPORT_TEST(ManyUnaryRequests) { &*this_call_index)); return handler.PullMessage(); }, - [handler, this_call_index, - &client_messages](NextResult msg) mutable { - EXPECT_TRUE(msg.has_value()); - EXPECT_EQ(msg.value()->payload()->JoinIntoString(), + [handler, this_call_index, &client_messages]( + ValueOrFailure> msg) mutable { + EXPECT_TRUE(msg.ok()); + EXPECT_TRUE(msg.value().has_value()); + EXPECT_EQ(msg.value().value()->payload()->JoinIntoString(), client_messages[*this_call_index]); return handler.PullMessage(); }, - [handler](NextResult msg) mutable { - EXPECT_FALSE(msg.has_value()); - EXPECT_FALSE(msg.cancelled()); + [handler](ValueOrFailure> msg) mutable { + EXPECT_TRUE(msg.ok()); + EXPECT_FALSE(msg.value().has_value()); auto md = Arena::MakePooled(); md->Set(ContentTypeMetadata(), ContentTypeMetadata::kApplicationGrpc); return handler.PushServerInitialMetadata(std::move(md)); @@ -118,10 +115,7 @@ TRANSPORT_TEST(ManyUnaryRequests) { EXPECT_TRUE(result.ok()); auto md = Arena::MakePooled(); md->Set(GrpcStatusMetadata(), GRPC_STATUS_UNIMPLEMENTED); - return handler.PushServerTrailingMetadata(std::move(md)); - }, - [handler](StatusFlag result) mutable { - EXPECT_TRUE(result.ok()); + handler.PushServerTrailingMetadata(std::move(md)); return Empty{}; }); } diff --git a/test/core/transport/test_suite/test.cc b/test/core/transport/test_suite/test.cc index 6d48a5712fa..7dc767810d7 100644 --- a/test/core/transport/test_suite/test.cc +++ b/test/core/transport/test_suite/test.cc @@ -56,12 +56,16 @@ void TransportTest::SetServerAcceptor() { transport_pair_.server->server_transport()->SetAcceptor(&acceptor_); } -CallInitiator TransportTest::CreateCall() { - auto call = MakeCall(event_engine_.get(), Arena::Create(1024, &allocator_)); - call.handler.SpawnInfallible("start-call", [this, handler = call.handler]() { - transport_pair_.client->client_transport()->StartCall(handler); - return Empty{}; - }); +CallInitiator TransportTest::CreateCall( + ClientMetadataHandle client_initial_metadata) { + auto call = MakeCall(std::move(client_initial_metadata), event_engine_.get(), + Arena::Create(1024, &allocator_), true); + call.handler.SpawnInfallible( + "start-call", [this, handler = call.handler]() mutable { + transport_pair_.client->client_transport()->StartCall( + handler.V2HackToStartCallWithoutACallFilterStack()); + return Empty{}; + }); return std::move(call.initiator); } @@ -231,9 +235,10 @@ Arena* TransportTest::Acceptor::CreateArena() { } absl::StatusOr TransportTest::Acceptor::CreateCall( - ClientMetadata&, Arena* arena) { - auto call = MakeCall(event_engine_, arena); - handlers_.push(std::move(call.handler)); + ClientMetadataHandle client_initial_metadata, Arena* arena) { + auto call = + MakeCall(std::move(client_initial_metadata), event_engine_, arena, true); + handlers_.push(call.handler.V2HackToStartCallWithoutACallFilterStack()); return std::move(call.initiator); } diff --git a/test/core/transport/test_suite/test.h b/test/core/transport/test_suite/test.h index 6981d5ca51f..5b0862a2744 100644 --- a/test/core/transport/test_suite/test.h +++ b/test/core/transport/test_suite/test.h @@ -130,9 +130,9 @@ PromiseSpawner SpawnerForContext( template using NextSpawner = absl::AnyInvocable; -template +template Promise WrapPromiseAndNext(std::shared_ptr action_state, - Promise promise, NextSpawner next) { + P promise, NextSpawner next) { return Promise(OnCancel( [action_state, promise = std::move(promise), next = std::move(next)]() mutable -> Poll { @@ -172,8 +172,7 @@ NextSpawner WrapFollowUps(NameAndLocation loc, action_state->Set(ActionState::kNotStarted); spawner(name, WrapPromiseAndNext(std::move(action_state), - Promise(factory.Make(std::move(arg))), - std::move(next))); + factory.Make(std::move(arg)), std::move(next))); }; } @@ -191,9 +190,9 @@ void StartSeq(NameAndLocation loc, ActionStateFactory action_state_factory, [spawner, first = Factory(std::move(first)), next = std::move(next), action_state = std::move(action_state), name = loc.name()]() mutable { action_state->Set(ActionState::kNotStarted); + auto promise = first.Make(); spawner(name, WrapPromiseAndNext(std::move(action_state), - Promise(first.Make()), - std::move(next))); + std::move(promise), std::move(next))); return Empty{}; }); } @@ -221,7 +220,7 @@ class TransportTest : public ::testing::Test { rng_(rng) {} void SetServerAcceptor(); - CallInitiator CreateCall(); + CallInitiator CreateCall(ClientMetadataHandle client_initial_metadata); std::string RandomString(int min_length, int max_length, absl::string_view character_set); @@ -272,7 +271,7 @@ class TransportTest : public ::testing::Test { Arena* CreateArena() override; absl::StatusOr CreateCall( - ClientMetadata& client_initial_metadata, Arena* arena) override; + ClientMetadataHandle client_initial_metadata, Arena* arena) override; absl::optional PopHandler(); private: diff --git a/test/core/tsi/alts/handshaker/alts_concurrent_connectivity_test.cc b/test/core/tsi/alts/handshaker/alts_concurrent_connectivity_test.cc index e7c50708564..e703c2a1fa8 100644 --- a/test/core/tsi/alts/handshaker/alts_concurrent_connectivity_test.cc +++ b/test/core/tsi/alts/handshaker/alts_concurrent_connectivity_test.cc @@ -34,6 +34,7 @@ #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" +#include #include #include #include diff --git a/test/core/tsi/alts/handshaker/alts_handshaker_client_test.cc b/test/core/tsi/alts/handshaker/alts_handshaker_client_test.cc index bbacdcfe45f..43502dbb8f2 100644 --- a/test/core/tsi/alts/handshaker/alts_handshaker_client_test.cc +++ b/test/core/tsi/alts/handshaker/alts_handshaker_client_test.cc @@ -22,6 +22,7 @@ #include "upb/mem/arena.hpp" +#include #include #include diff --git a/test/core/util/fake_stats_plugin.cc b/test/core/util/fake_stats_plugin.cc index 2ef159d5b75..00055d06d94 100644 --- a/test/core/util/fake_stats_plugin.cc +++ b/test/core/util/fake_stats_plugin.cc @@ -22,15 +22,16 @@ class FakeStatsClientFilter : public ChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + explicit FakeStatsClientFilter( + FakeClientCallTracerFactory* fake_client_call_tracer_factory); + + static absl::StatusOr> Create( const ChannelArgs& /*args*/, ChannelFilter::Args /*filter_args*/); ArenaPromise MakeCallPromise( CallArgs call_args, NextPromiseFactory next_promise_factory) override; private: - explicit FakeStatsClientFilter( - FakeClientCallTracerFactory* fake_client_call_tracer_factory); FakeClientCallTracerFactory* const fake_client_call_tracer_factory_; }; @@ -38,13 +39,15 @@ const grpc_channel_filter FakeStatsClientFilter::kFilter = MakePromiseBasedFilter( "fake_stats_client"); -absl::StatusOr FakeStatsClientFilter::Create( - const ChannelArgs& args, ChannelFilter::Args /*filter_args*/) { +absl::StatusOr> +FakeStatsClientFilter::Create(const ChannelArgs& args, + ChannelFilter::Args /*filter_args*/) { auto* fake_client_call_tracer_factory = args.GetPointer( GRPC_ARG_INJECT_FAKE_CLIENT_CALL_TRACER_FACTORY); GPR_ASSERT(fake_client_call_tracer_factory != nullptr); - return FakeStatsClientFilter(fake_client_call_tracer_factory); + return std::make_unique( + fake_client_call_tracer_factory); } ArenaPromise FakeStatsClientFilter::MakeCallPromise( diff --git a/test/core/util/port_server_client.cc b/test/core/util/port_server_client.cc index 8dc073fc7e2..fd651bc29a7 100644 --- a/test/core/util/port_server_client.cc +++ b/test/core/util/port_server_client.cc @@ -30,6 +30,7 @@ #include "absl/status/statusor.h" #include "absl/strings/str_format.h" +#include #include #include #include diff --git a/test/cpp/end2end/BUILD b/test/cpp/end2end/BUILD index d8a09d6d3c0..36125889baa 100644 --- a/test/cpp/end2end/BUILD +++ b/test/cpp/end2end/BUILD @@ -1068,6 +1068,7 @@ grpc_cc_test( grpc_cc_test( name = "ssl_credentials_test", + timeout = "long", srcs = ["ssl_credentials_test.cc"], data = [ "//src/core/tsi/test_creds:ca.pem", diff --git a/test/cpp/end2end/grpclb_end2end_test.cc b/test/cpp/end2end/grpclb_end2end_test.cc index 408f45c794b..91be4134f12 100644 --- a/test/cpp/end2end/grpclb_end2end_test.cc +++ b/test/cpp/end2end/grpclb_end2end_test.cc @@ -33,6 +33,7 @@ #include "absl/synchronization/notification.h" #include "absl/types/span.h" +#include #include #include #include diff --git a/test/cpp/end2end/rls_end2end_test.cc b/test/cpp/end2end/rls_end2end_test.cc index 942c183b890..6f52a802f8c 100644 --- a/test/cpp/end2end/rls_end2end_test.cc +++ b/test/cpp/end2end/rls_end2end_test.cc @@ -33,6 +33,7 @@ #include "absl/strings/str_join.h" #include "absl/types/optional.h" +#include #include #include #include diff --git a/test/cpp/end2end/ssl_credentials_test.cc b/test/cpp/end2end/ssl_credentials_test.cc index a0b8d5c0dd2..092fe427aed 100644 --- a/test/cpp/end2end/ssl_credentials_test.cc +++ b/test/cpp/end2end/ssl_credentials_test.cc @@ -15,13 +15,18 @@ // limitations under the License. // // +#include "src/core/lib/security/credentials/ssl/ssl_credentials.h" + #include +#include +#include #include #include #include "absl/synchronization/notification.h" +#include #include #include #include @@ -29,34 +34,67 @@ #include #include +#include "src/core/lib/gprpp/cpp_impl_of.h" +#include "src/core/tsi/ssl_transport_security.h" +#include "src/cpp/client/secure_credentials.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #include "test/core/util/tls_utils.h" #include "test/cpp/end2end/test_service_impl.h" +// TODO(matthewstevenson88): More test cases to add: +// - Use P256, P384, P512 credentials. +// - Use a long certificate chain. +// - Use a large certificate. +// - Large trust bundle. +// - Bad ALPN. +// - More failure modes. +// - Certs containing more SANs. +// - Copy all of this over to tls_credentials_test.cc. +// - Client doesn't have cert but server requests one. +// - Bad session ticket in cache. +// - Use same channel creds object on sequential/concurrent handshakes. +// - Do successful handshake with a localhost server cert. +// - Missing or malformed roots on both sides. + namespace grpc { namespace testing { namespace { +using ::grpc_core::testing::GetFileContents; +using ::testing::HasSubstr; +using ::testing::IsEmpty; +using ::testing::UnorderedElementsAre; + constexpr char kCaCertPath[] = "src/core/tsi/test_creds/ca.pem"; constexpr char kServerCertPath[] = "src/core/tsi/test_creds/server1.pem"; constexpr char kServerKeyPath[] = "src/core/tsi/test_creds/server1.key"; constexpr char kClientCertPath[] = "src/core/tsi/test_creds/client.pem"; constexpr char kClientKeyPath[] = "src/core/tsi/test_creds/client.key"; constexpr char kMessage[] = "Hello"; +constexpr char kTargetNameOverride[] = "foo.test.google.fr"; + +std::size_t GetSessionCacheSize(grpc_ssl_session_cache* cache) { + tsi_ssl_session_cache* tsi_cache = + reinterpret_cast(cache); + return tsi_ssl_session_cache_size(tsi_cache); +} + +struct SslOptions { + grpc_ssl_client_certificate_request_type request_type = + GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; + bool use_session_cache; +}; -class SslCredentialsTest : public ::testing::Test { +class SslCredentialsTest : public ::testing::TestWithParam { protected: - void RunServer(absl::Notification* notification) { - std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath); + void RunServer(absl::Notification* notification, + absl::string_view pem_root_certs) { grpc::SslServerCredentialsOptions::PemKeyCertPair key_cert_pair = { - grpc_core::testing::GetFileContents(kServerKeyPath), - grpc_core::testing::GetFileContents(kServerCertPath)}; - // TODO(gtcooke94) Parametrize this test for TLS and mTLS as well - grpc::SslServerCredentialsOptions ssl_options; + GetFileContents(kServerKeyPath), GetFileContents(kServerCertPath)}; + grpc::SslServerCredentialsOptions ssl_options(GetParam().request_type); ssl_options.pem_key_cert_pairs.push_back(key_cert_pair); - ssl_options.pem_root_certs = root_cert; - ssl_options.force_client_auth = true; + ssl_options.pem_root_certs = std::string(pem_root_certs); grpc::ServerBuilder builder; TestServiceImpl service_; @@ -77,57 +115,226 @@ class SslCredentialsTest : public ::testing::Test { } } + absl::StatusOr> DoRpc( + const SslCredentialsOptions& options, grpc_ssl_session_cache* cache, + bool override_ssl_target_name = true) { + ChannelArguments channel_args; + if (GetParam().use_session_cache) { + channel_args.SetPointer(std::string(GRPC_SSL_SESSION_CACHE_ARG), cache); + } + if (override_ssl_target_name) { + channel_args.SetSslTargetNameOverride(kTargetNameOverride); + } + + auto creds = SslCredentials(options); + std::shared_ptr channel = + grpc::CreateCustomChannel(server_addr_, creds, channel_args); + + auto stub = grpc::testing::EchoTestService::NewStub(channel); + grpc::testing::EchoRequest request; + grpc::testing::EchoResponse response; + request.set_message(kMessage); + ClientContext context; + context.set_deadline(grpc_timeout_seconds_to_deadline(/*time_s=*/10)); + grpc::Status result = stub->Echo(&context, request, &response); + if (!result.ok()) { + return absl::Status(static_cast(result.error_code()), + result.error_message()); + } + EXPECT_EQ(response.message(), kMessage); + return context.auth_context(); + } + + static std::vector GetAuthContextPropertyAsList( + const AuthContext& auth_context, const std::string& property) { + std::vector properties; + for (const grpc::string_ref& property : + auth_context.FindPropertyValues(property)) { + properties.push_back(absl::string_view(property.data(), property.size())); + } + return properties; + } + + static absl::string_view GetAuthContextProperty( + const AuthContext& auth_context, const std::string& property) { + std::vector properties = + GetAuthContextPropertyAsList(auth_context, property); + return properties.size() == 1 ? properties[0] : ""; + } + TestServiceImpl service_; std::unique_ptr server_ = nullptr; std::thread* server_thread_ = nullptr; std::string server_addr_; }; -void DoRpc(const std::string& server_addr, - const SslCredentialsOptions& ssl_options, - grpc_ssl_session_cache* cache, bool expect_session_reuse) { - ChannelArguments channel_args; - channel_args.SetPointer(std::string(GRPC_SSL_SESSION_CACHE_ARG), cache); - channel_args.SetSslTargetNameOverride("foo.test.google.fr"); - - std::shared_ptr channel = grpc::CreateCustomChannel( - server_addr, grpc::SslCredentials(ssl_options), channel_args); - - auto stub = grpc::testing::EchoTestService::NewStub(channel); - grpc::testing::EchoRequest request; - grpc::testing::EchoResponse response; - request.set_message(kMessage); - ClientContext context; - context.set_deadline(grpc_timeout_seconds_to_deadline(/*time_s=*/10)); - grpc::Status result = stub->Echo(&context, request, &response); - EXPECT_TRUE(result.ok()); - if (!result.ok()) { - gpr_log(GPR_ERROR, "%s, %s", result.error_message().c_str(), - result.error_details().c_str()); - } - EXPECT_EQ(response.message(), kMessage); - std::shared_ptr auth_context = context.auth_context(); - std::vector properties = - auth_context->FindPropertyValues(GRPC_SSL_SESSION_REUSED_PROPERTY); - ASSERT_EQ(properties.size(), 1u); - if (expect_session_reuse) { - EXPECT_EQ("true", ToString(properties[0])); - } else { - EXPECT_EQ("false", ToString(properties[0])); +TEST_P(SslCredentialsTest, FullHandshake) { + server_addr_ = absl::StrCat("localhost:", + std::to_string(grpc_pick_unused_port_or_die())); + absl::Notification notification; + server_thread_ = new std::thread([&]() { + std::string root_cert = GetFileContents(kCaCertPath); + RunServer(¬ification, root_cert); + }); + notification.WaitForNotification(); + + std::string root_cert = GetFileContents(kCaCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); + grpc::SslCredentialsOptions ssl_options; + ssl_options.pem_root_certs = root_cert; + ssl_options.pem_private_key = client_key; + ssl_options.pem_cert_chain = client_cert; + + grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(16); + + auto full_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(full_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "false"); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME), + GRPC_SSL_TRANSPORT_SECURITY_TYPE); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME), + "TSI_PRIVACY_AND_INTEGRITY"); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_X509_CN_PROPERTY_NAME), + "*.test.google.com"); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_X509_SUBJECT_PROPERTY_NAME), + "CN=*.test.google.com,O=Example\\, Co.,L=Chicago,ST=Illinois,C=US"); + EXPECT_THAT( + GetAuthContextPropertyAsList(**full_handshake_context, + GRPC_X509_SAN_PROPERTY_NAME), + UnorderedElementsAre("*.test.google.fr", "waterzooi.test.google.be", + "*.test.youtube.com", "192.168.1.3")); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_X509_PEM_CERT_PROPERTY_NAME), + GetFileContents(kServerCertPath)); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME), + GetFileContents(kServerCertPath)); + EXPECT_THAT( + GetAuthContextPropertyAsList(**full_handshake_context, + GRPC_PEER_DNS_PROPERTY_NAME), + UnorderedElementsAre("*.test.google.fr", "waterzooi.test.google.be", + "*.test.youtube.com")); + EXPECT_THAT(GetAuthContextPropertyAsList(**full_handshake_context, + GRPC_PEER_URI_PROPERTY_NAME), + IsEmpty()); + EXPECT_THAT(GetAuthContextPropertyAsList(**full_handshake_context, + GRPC_PEER_EMAIL_PROPERTY_NAME), + IsEmpty()); + EXPECT_THAT(GetAuthContextPropertyAsList(**full_handshake_context, + GRPC_PEER_IP_PROPERTY_NAME), + UnorderedElementsAre("192.168.1.3")); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_PEER_SPIFFE_ID_PROPERTY_NAME), + ""); + if (GetParam().use_session_cache) { + EXPECT_EQ(GetSessionCacheSize(cache), 1); } + + grpc_ssl_session_cache_destroy(cache); +} + +TEST_P(SslCredentialsTest, ResumedHandshake) { + // Skip this test if session caching is disabled. + if (!GetParam().use_session_cache) return; + + server_addr_ = absl::StrCat("localhost:", + std::to_string(grpc_pick_unused_port_or_die())); + absl::Notification notification; + server_thread_ = new std::thread([&]() { + std::string root_cert = GetFileContents(kCaCertPath); + RunServer(¬ification, root_cert); + }); + notification.WaitForNotification(); + + std::string root_cert = GetFileContents(kCaCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); + grpc::SslCredentialsOptions ssl_options; + ssl_options.pem_root_certs = root_cert; + ssl_options.pem_private_key = client_key; + ssl_options.pem_cert_chain = client_cert; + + grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(16); + + auto full_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(full_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "false"); + + auto resumed_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(resumed_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "true"); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME), + GRPC_SSL_TRANSPORT_SECURITY_TYPE); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME), + "TSI_PRIVACY_AND_INTEGRITY"); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_X509_CN_PROPERTY_NAME), + "*.test.google.com"); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_X509_SUBJECT_PROPERTY_NAME), + "CN=*.test.google.com,O=Example\\, Co.,L=Chicago,ST=Illinois,C=US"); + EXPECT_THAT( + GetAuthContextPropertyAsList(**resumed_handshake_context, + GRPC_X509_SAN_PROPERTY_NAME), + UnorderedElementsAre("*.test.google.fr", "waterzooi.test.google.be", + "*.test.youtube.com", "192.168.1.3")); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_X509_PEM_CERT_PROPERTY_NAME), + GetFileContents(kServerCertPath)); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME), + GetFileContents(kServerCertPath)); + EXPECT_THAT( + GetAuthContextPropertyAsList(**resumed_handshake_context, + GRPC_PEER_DNS_PROPERTY_NAME), + UnorderedElementsAre("*.test.google.fr", "waterzooi.test.google.be", + "*.test.youtube.com")); + EXPECT_THAT(GetAuthContextPropertyAsList(**resumed_handshake_context, + GRPC_PEER_URI_PROPERTY_NAME), + IsEmpty()); + EXPECT_THAT(GetAuthContextPropertyAsList(**resumed_handshake_context, + GRPC_PEER_EMAIL_PROPERTY_NAME), + IsEmpty()); + EXPECT_THAT(GetAuthContextPropertyAsList(**resumed_handshake_context, + GRPC_PEER_IP_PROPERTY_NAME), + UnorderedElementsAre("192.168.1.3")); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_PEER_SPIFFE_ID_PROPERTY_NAME), + ""); + EXPECT_EQ(GetSessionCacheSize(cache), 1); + + grpc_ssl_session_cache_destroy(cache); } -TEST_F(SslCredentialsTest, SequentialResumption) { +TEST_P(SslCredentialsTest, SequentialResumption) { + // Skip this test if session caching is disabled. + if (!GetParam().use_session_cache) return; + server_addr_ = absl::StrCat("localhost:", std::to_string(grpc_pick_unused_port_or_die())); absl::Notification notification; - server_thread_ = new std::thread([&]() { RunServer(¬ification); }); + server_thread_ = new std::thread([&]() { + std::string root_cert = GetFileContents(kCaCertPath); + RunServer(¬ification, root_cert); + }); notification.WaitForNotification(); - std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath); - std::string client_key = grpc_core::testing::GetFileContents(kClientKeyPath); - std::string client_cert = - grpc_core::testing::GetFileContents(kClientCertPath); + std::string root_cert = GetFileContents(kCaCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); grpc::SslCredentialsOptions ssl_options; ssl_options.pem_root_certs = root_cert; ssl_options.pem_private_key = client_key; @@ -135,25 +342,38 @@ TEST_F(SslCredentialsTest, SequentialResumption) { grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(16); - DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false); + auto full_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(full_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "false"); for (int i = 0; i < 10; i++) { - DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/true); + auto resumed_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(resumed_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "true"); } grpc_ssl_session_cache_destroy(cache); } -TEST_F(SslCredentialsTest, ConcurrentResumption) { +TEST_P(SslCredentialsTest, ConcurrentResumption) { + // Skip this test if session caching is disabled. + if (!GetParam().use_session_cache) return; + server_addr_ = absl::StrCat("localhost:", std::to_string(grpc_pick_unused_port_or_die())); absl::Notification notification; - server_thread_ = new std::thread([&]() { RunServer(¬ification); }); + server_thread_ = new std::thread([&]() { + std::string root_cert = GetFileContents(kCaCertPath); + RunServer(¬ification, root_cert); + }); notification.WaitForNotification(); - std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath); - std::string client_key = grpc_core::testing::GetFileContents(kClientKeyPath); - std::string client_cert = - grpc_core::testing::GetFileContents(kClientCertPath); + std::string root_cert = GetFileContents(kCaCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); grpc::SslCredentialsOptions ssl_options; ssl_options.pem_root_certs = root_cert; ssl_options.pem_private_key = client_key; @@ -161,12 +381,20 @@ TEST_F(SslCredentialsTest, ConcurrentResumption) { grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(16); - DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false); + auto full_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(full_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "false"); std::vector threads; threads.reserve(10); for (int i = 0; i < 10; i++) { threads.push_back(std::thread([&]() { - DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/true); + auto resumed_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(resumed_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**resumed_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "true"); })); } for (auto& t : threads) { @@ -176,17 +404,19 @@ TEST_F(SslCredentialsTest, ConcurrentResumption) { grpc_ssl_session_cache_destroy(cache); } -TEST_F(SslCredentialsTest, ResumptionFailsDueToNoCapacityInCache) { +TEST_P(SslCredentialsTest, ResumptionFailsDueToNoCapacityInCache) { server_addr_ = absl::StrCat("localhost:", std::to_string(grpc_pick_unused_port_or_die())); absl::Notification notification; - server_thread_ = new std::thread([&]() { RunServer(¬ification); }); + server_thread_ = new std::thread([&]() { + std::string root_cert = GetFileContents(kCaCertPath); + RunServer(¬ification, root_cert); + }); notification.WaitForNotification(); - std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath); - std::string client_key = grpc_core::testing::GetFileContents(kClientKeyPath); - std::string client_cert = - grpc_core::testing::GetFileContents(kClientCertPath); + std::string root_cert = GetFileContents(kCaCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); grpc::SslCredentialsOptions ssl_options; ssl_options.pem_root_certs = root_cert; ssl_options.pem_private_key = client_key; @@ -194,12 +424,152 @@ TEST_F(SslCredentialsTest, ResumptionFailsDueToNoCapacityInCache) { grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(0); - DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false); - DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false); + for (int i = 0; i < 2; ++i) { + auto full_handshake_context = DoRpc(ssl_options, cache); + EXPECT_EQ(full_handshake_context.status(), absl::OkStatus()); + EXPECT_EQ(GetAuthContextProperty(**full_handshake_context, + GRPC_SSL_SESSION_REUSED_PROPERTY), + "false"); + } grpc_ssl_session_cache_destroy(cache); } +TEST_P(SslCredentialsTest, ServerCertificateIsUntrusted) { + server_addr_ = absl::StrCat("localhost:", + std::to_string(grpc_pick_unused_port_or_die())); + absl::Notification notification; + server_thread_ = new std::thread([&]() { + std::string root_cert = GetFileContents(kCaCertPath); + RunServer(¬ification, root_cert); + }); + notification.WaitForNotification(); + + // Use the client's own leaf cert as the root cert, so that the server's cert + // will not be trusted by the client. + std::string root_cert = GetFileContents(kClientCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); + grpc::SslCredentialsOptions ssl_options; + ssl_options.pem_root_certs = root_cert; + ssl_options.pem_private_key = client_key; + ssl_options.pem_cert_chain = client_cert; + + grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(0); + + auto auth_context = DoRpc(ssl_options, cache); + EXPECT_EQ(auth_context.status().code(), absl::StatusCode::kUnavailable); + EXPECT_THAT(auth_context.status().message(), + HasSubstr("CERTIFICATE_VERIFY_FAILED")); + EXPECT_EQ(GetSessionCacheSize(cache), 0); + + grpc_ssl_session_cache_destroy(cache); +} + +TEST_P(SslCredentialsTest, ClientCertificateIsUntrusted) { + // Skip this test if the client certificate is not requested. + if (GetParam().request_type == grpc_ssl_client_certificate_request_type:: + GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE) { + return; + } + + server_addr_ = absl::StrCat("localhost:", + std::to_string(grpc_pick_unused_port_or_die())); + absl::Notification notification; + server_thread_ = new std::thread([&]() { + // Use the server's own leaf cert as the root cert, so that the client's + // cert will not be trusted by the server. + std::string root_cert = GetFileContents(kServerCertPath); + RunServer(¬ification, root_cert); + }); + notification.WaitForNotification(); + + std::string root_cert = GetFileContents(kCaCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); + grpc::SslCredentialsOptions ssl_options; + ssl_options.pem_root_certs = root_cert; + ssl_options.pem_private_key = client_key; + ssl_options.pem_cert_chain = client_cert; + + grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(0); + + auto auth_context = DoRpc(ssl_options, cache); + if (GetParam().request_type == + grpc_ssl_client_certificate_request_type:: + GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY || + GetParam().request_type == + grpc_ssl_client_certificate_request_type:: + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY) { + EXPECT_EQ(auth_context.status().code(), absl::StatusCode::kUnavailable); + // TODO(matthewstevenson88): Investigate having a more descriptive error + // message for the client. + EXPECT_THAT(auth_context.status().message(), + HasSubstr("failed to connect")); + EXPECT_EQ(GetSessionCacheSize(cache), 0); + } else { + // TODO(matthewstevenson88): The handshake fails with a certificate + // verification error in these cases. This is a bug. Fix this. + } + + grpc_ssl_session_cache_destroy(cache); +} + +TEST_P(SslCredentialsTest, ServerHostnameVerificationFails) { + server_addr_ = absl::StrCat("localhost:", + std::to_string(grpc_pick_unused_port_or_die())); + absl::Notification notification; + server_thread_ = new std::thread([&]() { + std::string root_cert = GetFileContents(kCaCertPath); + RunServer(¬ification, root_cert); + }); + notification.WaitForNotification(); + + std::string root_cert = GetFileContents(kCaCertPath); + std::string client_key = GetFileContents(kClientKeyPath); + std::string client_cert = GetFileContents(kClientCertPath); + grpc::SslCredentialsOptions ssl_options; + ssl_options.pem_root_certs = root_cert; + ssl_options.pem_private_key = client_key; + ssl_options.pem_cert_chain = client_cert; + + grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(0); + + auto auth_context = + DoRpc(ssl_options, cache, /*override_ssl_target_name=*/false); + EXPECT_EQ(auth_context.status().code(), absl::StatusCode::kUnavailable); + // TODO(matthewstevenson88): Logs say "No match found for server name: + // localhost." but this error is not propagated to the user. Fix this. + EXPECT_FALSE(auth_context.status().message().empty()); + EXPECT_EQ(GetSessionCacheSize(cache), 0); + + grpc_ssl_session_cache_destroy(cache); +} + +std::vector GetSslOptions() { + std::vector ssl_options; + for (grpc_ssl_client_certificate_request_type type : + {grpc_ssl_client_certificate_request_type:: + GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE, + grpc_ssl_client_certificate_request_type:: + GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY, + grpc_ssl_client_certificate_request_type:: + GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY, + grpc_ssl_client_certificate_request_type:: + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY, + grpc_ssl_client_certificate_request_type:: + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY}) { + for (bool use_session_cache : {false, true}) { + SslOptions option = {type, use_session_cache}; + ssl_options.push_back(option); + } + } + return ssl_options; +} + +INSTANTIATE_TEST_SUITE_P(SslCredentials, SslCredentialsTest, + ::testing::ValuesIn(GetSslOptions())); + } // namespace } // namespace testing } // namespace grpc diff --git a/test/cpp/ext/otel/otel_test_library.cc b/test/cpp/ext/otel/otel_test_library.cc index 0aac08a4da3..81ab0842128 100644 --- a/test/cpp/ext/otel/otel_test_library.cc +++ b/test/cpp/ext/otel/otel_test_library.cc @@ -50,9 +50,15 @@ class AddLabelsFilter : public grpc_core::ChannelFilter { public: static const grpc_channel_filter kFilter; - static absl::StatusOr Create( + explicit AddLabelsFilter( + std::map + labels_to_inject) + : labels_to_inject_(std::move(labels_to_inject)) {} + + static absl::StatusOr> Create( const grpc_core::ChannelArgs& args, ChannelFilter::Args /*filter_args*/) { - return AddLabelsFilter( + return absl::make_unique( *args.GetPointer>(GRPC_ARG_LABELS_TO_INJECT)); @@ -73,12 +79,6 @@ class AddLabelsFilter : public grpc_core::ChannelFilter { } private: - explicit AddLabelsFilter( - std::map - labels_to_inject) - : labels_to_inject_(std::move(labels_to_inject)) {} - const std::map< grpc_core::ClientCallTracer::CallAttemptTracer::OptionalLabelKey, grpc_core::RefCountedStringValue> diff --git a/test/cpp/interop/client_helper.cc b/test/cpp/interop/client_helper.cc index 523de360bd6..d9d10f1eeb9 100644 --- a/test/cpp/interop/client_helper.cc +++ b/test/cpp/interop/client_helper.cc @@ -28,6 +28,7 @@ #include "absl/strings/escaping.h" #include "absl/strings/match.h" +#include #include #include #include diff --git a/test/cpp/microbenchmarks/bm_channel.cc b/test/cpp/microbenchmarks/bm_channel.cc index c4b62a304c0..ff9baf59b70 100644 --- a/test/cpp/microbenchmarks/bm_channel.cc +++ b/test/cpp/microbenchmarks/bm_channel.cc @@ -20,6 +20,7 @@ #include +#include #include #include diff --git a/test/cpp/naming/cancel_ares_query_test.cc b/test/cpp/naming/cancel_ares_query_test.cc index c2009ae970a..9b6cacafd49 100644 --- a/test/cpp/naming/cancel_ares_query_test.cc +++ b/test/cpp/naming/cancel_ares_query_test.cc @@ -27,6 +27,7 @@ #include "absl/strings/str_format.h" #include +#include #include #include #include diff --git a/test/cpp/server/BUILD b/test/cpp/server/BUILD index 0927de6c7a0..063e6cf2a4c 100644 --- a/test/cpp/server/BUILD +++ b/test/cpp/server/BUILD @@ -28,6 +28,7 @@ grpc_cc_test( deps = [ "//:grpc++_unsecure", "//src/proto/grpc/testing:echo_proto", + "//test/core/event_engine:event_engine_test_utils", "//test/core/util:grpc_test_util_base", "//test/core/util:grpc_test_util_unsecure", ], diff --git a/test/cpp/server/server_builder_test.cc b/test/cpp/server/server_builder_test.cc index 14eaa5efb7d..476eb41686c 100644 --- a/test/cpp/server/server_builder_test.cc +++ b/test/cpp/server/server_builder_test.cc @@ -16,14 +16,19 @@ // // +#include + #include +#include #include #include #include #include +#include "src/core/lib/gprpp/notification.h" #include "src/proto/grpc/testing/echo.grpc.pb.h" +#include "test/core/event_engine/event_engine_test_utils.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" @@ -83,6 +88,56 @@ TEST_F(ServerBuilderTest, CreateServerRepeatedPortWithDisallowedReusePort) { nullptr); } +TEST_F(ServerBuilderTest, AddPassiveListener) { + std::unique_ptr passive_listener; + auto server = + ServerBuilder() + .experimental() + .AddPassiveListener(InsecureServerCredentials(), passive_listener) + .BuildAndStart(); + server->Shutdown(); +} + +TEST_F(ServerBuilderTest, PassiveListenerAcceptConnectedFd) { + std::unique_ptr passive_listener; + ServerBuilder builder; + auto cq = builder.AddCompletionQueue(); + // TODO(hork): why is the service necessary? Queue isn't drained otherwise. + auto server = + builder.RegisterService(&g_service) + .experimental() + .AddPassiveListener(InsecureServerCredentials(), passive_listener) + .BuildAndStart(); + ASSERT_NE(server.get(), nullptr); +#ifdef GPR_SUPPORT_CHANNELS_FROM_FD + int fd = socket(AF_INET, SOCK_STREAM, 0); + auto accept_status = passive_listener->AcceptConnectedFd(fd); + ASSERT_TRUE(accept_status.ok()) << accept_status; +#else + int fd = -1; + auto accept_status = passive_listener->AcceptConnectedFd(fd); + ASSERT_FALSE(accept_status.ok()) << accept_status; +#endif + server->Shutdown(); +} + +TEST_F(ServerBuilderTest, PassiveListenerAcceptConnectedEndpoint) { + std::unique_ptr passive_listener; + auto server = + ServerBuilder() + .experimental() + .AddPassiveListener(InsecureServerCredentials(), passive_listener) + .BuildAndStart(); + grpc_core::Notification endpoint_destroyed; + auto success = passive_listener->AcceptConnectedEndpoint( + std::make_unique( + &endpoint_destroyed)); + ASSERT_TRUE(success.ok()) + << "AcceptConnectedEndpoint failure: " << success.ToString(); + endpoint_destroyed.WaitForNotification(); + server->Shutdown(); +} + } // namespace } // namespace grpc diff --git a/test/cpp/util/grpc_tool.cc b/test/cpp/util/grpc_tool.cc index c1ebecd333b..95c8bc3d83b 100644 --- a/test/cpp/util/grpc_tool.cc +++ b/test/cpp/util/grpc_tool.cc @@ -25,9 +25,12 @@ #include #include #include +#include #include "absl/flags/flag.h" -#include "absl/memory/memory.h" +#include "absl/strings/numbers.h" +#include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" #include #include @@ -82,6 +85,9 @@ ABSL_FLAG( int, max_recv_msg_size, 0, "Specify the max receive message size in bytes for all RPCs. -1 indicates " "unlimited. The default value of 0 means to use the gRPC default."); +ABSL_FLAG(std::string, channel_args, "", + "Comma-separated list of key=value gRPC ChannelArgs to apply " + "(a=b,c=d,...). Values may be integers or strings."); namespace grpc { namespace testing { @@ -244,6 +250,20 @@ std::shared_ptr CreateCliChannel( // See |GRPC_ARG_MAX_METADATA_SIZE| in |grpc_types.h|. // Set to large enough size (10M) that should work for most use cases. args.SetInt(GRPC_ARG_MAX_METADATA_SIZE, 10 * 1024 * 1024); + + // Extend channel args according to flag --channel_args. + const auto flag = absl::GetFlag(FLAGS_channel_args); + for (absl::string_view arg : + absl::StrSplit(flag, ',', absl::SkipWhitespace())) { + std::pair kv = + absl::StrSplit(arg, absl::MaxSplits('=', 1), absl::SkipWhitespace()); + int ival; + if (absl::SimpleAtoi(kv.second, &ival)) { + args.SetInt(kv.first, ival); + } else if (!kv.second.empty()) { + args.SetString(kv.first, kv.second); + } + } return grpc::CreateCustomChannel(server_address, cred.GetCredentials(), args); } diff --git a/test/cpp/util/grpc_tool_test.cc b/test/cpp/util/grpc_tool_test.cc index 1148c182666..057a0008b8e 100644 --- a/test/cpp/util/grpc_tool_test.cc +++ b/test/cpp/util/grpc_tool_test.cc @@ -133,6 +133,7 @@ ABSL_DECLARE_FLAG(std::string, proto_path); ABSL_DECLARE_FLAG(std::string, default_service_config); ABSL_DECLARE_FLAG(double, timeout); ABSL_DECLARE_FLAG(int, max_recv_msg_size); +ABSL_DECLARE_FLAG(std::string, channel_args); namespace grpc { namespace testing { @@ -1299,11 +1300,11 @@ TEST_F(GrpcToolTest, CallMaxRecvMessageSizeSmall) { // Set max_recv_msg_size to 4 which is not enough. absl::SetFlag(&FLAGS_max_recv_msg_size, 4); - - // This should fail. EXPECT_FALSE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); + absl::SetFlag(&FLAGS_max_recv_msg_size, 0); + // No output expected. EXPECT_TRUE(0 == output_stream.tellp()); ShutdownServer(); @@ -1320,10 +1321,11 @@ TEST_F(GrpcToolTest, CallMaxRecvMessageSizeEnough) { // Set max_recv_msg_size to a large enough number. absl::SetFlag(&FLAGS_max_recv_msg_size, 1024 * 1024); - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); + absl::SetFlag(&FLAGS_max_recv_msg_size, 0); + // Expected output: "message: \"Hello\"" EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), "message: \"Hello\"")); @@ -1341,10 +1343,10 @@ TEST_F(GrpcToolTest, CallMaxRecvMessageSizeDefault) { // Set max_recv_msg_size to gRPC default, which should suffice. absl::SetFlag(&FLAGS_max_recv_msg_size, 0); - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); + // Expected output: "message: \"Hello\"" EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), "message: \"Hello\"")); @@ -1362,16 +1364,46 @@ TEST_F(GrpcToolTest, CallMaxRecvMessageSizeUnlimited) { // Set max_recv_msg_size to unlimited (-1), which should work. absl::SetFlag(&FLAGS_max_recv_msg_size, -1); - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); + absl::SetFlag(&FLAGS_max_recv_msg_size, 0); + // Expected output: "message: \"Hello\"" EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), "message: \"Hello\"")); ShutdownServer(); } +// This duplicates CallMaxRecvMessageSizeSmall, but using --channel_args. +TEST_F(GrpcToolTest, CallWithChannelArgs) { + std::stringstream output_stream; + const std::string server_address = SetUpServer(); + // Test input "grpc_cli call localhost:10000 Echo "message: 'Hello' + // --channel_args=grpc.max_receive_message_length=4" + const char* argv[] = {"grpc_cli", "call", server_address.c_str(), + "grpc.testing.EchoTestService.Echo", + "message: 'Hello'"}; + + // Set max receive size to 4 bytes which is not enough. + absl::SetFlag(&FLAGS_channel_args, + "x=y,grpc.max_receive_message_length=4,z=1"); + EXPECT_FALSE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + absl::SetFlag(&FLAGS_channel_args, ""); + + // Then try again with large enough size, which should succeed. + absl::SetFlag(&FLAGS_channel_args, + ",grpc.max_receive_message_length=1000000,"); + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + absl::SetFlag(&FLAGS_channel_args, ""); + + ShutdownServer(); +} + TEST_F(GrpcToolTest, ListCommandOverrideSslHostName) { const std::string server_address = SetUpServer(true); diff --git a/test/distrib/python/test_packages.sh b/test/distrib/python/test_packages.sh index 136632833b1..fa6f2fceeeb 100755 --- a/test/distrib/python/test_packages.sh +++ b/test/distrib/python/test_packages.sh @@ -19,22 +19,25 @@ cd "$(dirname "$0")" shopt -s nullglob +echo "Testing Python packages with input artifacts:" +ls "$EXTERNAL_GIT_ROOT"/input_artifacts + if [[ "$1" == "binary" ]] then echo "Testing Python binary distribution" - ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio-[0-9]*.whl) - TOOLS_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio_tools-[0-9]*.whl) - OBSERVABILITY_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio_observability-[0-9]*.whl) + ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[-_0-9a-z.]*.whl) + TOOLS_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[_-]*tools[-_0-9a-z.]*.whl) + OBSERVABILITY_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[_-]*observability[-_0-9a-z.]*.whl) else echo "Testing Python source distribution" - ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio-[0-9]*.tar.gz) - TOOLS_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio-tools-[0-9]*.tar.gz) - OBSERVABILITY_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio-observability-[0-9]*.tar.gz) + ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[-_0-9a-z.]*.tar.gz) + TOOLS_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[_-]*tools[-_0-9a-z.]*.tar.gz) + OBSERVABILITY_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[_-]*observability[-_0-9a-z.]*.tar.gz) fi -HEALTH_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio-health-checking-[0-9]*.tar.gz) -REFLECTION_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio-reflection-[0-9]*.tar.gz) -TESTING_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio-testing-[0-9]*.tar.gz) +HEALTH_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[_-]*health[_-]*checking[-_0-9a-z.]*.tar.gz) +REFLECTION_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[_-]*reflection[-_0-9a-z.]*.tar.gz) +TESTING_ARCHIVES=("$EXTERNAL_GIT_ROOT"/input_artifacts/grpcio[_-]*testing[-_0-9a-z.]*.tar.gz) VIRTUAL_ENV=$(mktemp -d) python3 -m virtualenv "$VIRTUAL_ENV" diff --git a/tools/codegen/core/gen_grpc_tls_credentials_options.py b/tools/codegen/core/gen_grpc_tls_credentials_options.py index 1c802bee886..b0a6d01ebbb 100755 --- a/tools/codegen/core/gen_grpc_tls_credentials_options.py +++ b/tools/codegen/core/gen_grpc_tls_credentials_options.py @@ -305,6 +305,7 @@ print( #include "absl/container/inlined_vector.h" +#include #include #include "src/core/lib/gprpp/ref_counted.h" @@ -469,6 +470,8 @@ print( #include +#include + #include "src/core/lib/security/credentials/xds/xds_credentials.h" #include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h" #include "test/core/util/test_config.h" diff --git a/tools/distrib/check_namespace_qualification.py b/tools/distrib/check_namespace_qualification.py index 6634d8b8830..bf13f0cd729 100755 --- a/tools/distrib/check_namespace_qualification.py +++ b/tools/distrib/check_namespace_qualification.py @@ -77,6 +77,10 @@ IGNORED_FILES = [ "src/core/lib/gprpp/global_config_env.h", "src/core/lib/profiling/timers.h", "src/core/lib/gprpp/crash.h", + # The grpc_core::Server redundant namespace qualification is required for + # older gcc versions. + "src/core/ext/transport/chttp2/server/chttp2_server.h", + "src/core/lib/surface/server.h", ] # find our home diff --git a/tools/distrib/check_redundant_namespace_qualifiers.py b/tools/distrib/check_redundant_namespace_qualifiers.py index 0322332209b..db89796db6f 100755 --- a/tools/distrib/check_redundant_namespace_qualifiers.py +++ b/tools/distrib/check_redundant_namespace_qualifiers.py @@ -21,6 +21,13 @@ import os import re import sys +IGNORED_FILES = [ + # note: the grpc_core::Server redundant namespace qualification is required + # for older gcc versions. + "src/core/ext/transport/chttp2/server/chttp2_server.h", + "src/core/lib/surface/server.h", +] + def find_closing_mustache(contents, initial_depth): """Find the closing mustache for a given number of open mustaches.""" @@ -166,6 +173,8 @@ for config in _CONFIGURATION: for file in files: if file.endswith(".cc") or file.endswith(".h"): path = os.path.join(root, file) + if path in IGNORED_FILES: + continue try: with open(path) as f: contents = f.read() diff --git a/tools/doxygen/Doxyfile.c++ b/tools/doxygen/Doxyfile.c++ index a6bb91ebf02..c630913e944 100644 --- a/tools/doxygen/Doxyfile.c++ +++ b/tools/doxygen/Doxyfile.c++ @@ -880,6 +880,7 @@ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/census.h \ include/grpc/compression.h \ +include/grpc/credentials.h \ include/grpc/event_engine/endpoint_config.h \ include/grpc/event_engine/event_engine.h \ include/grpc/event_engine/extensible.h \ @@ -927,6 +928,7 @@ include/grpc/impl/grpc_types.h \ include/grpc/impl/propagation_bits.h \ include/grpc/impl/slice_type.h \ include/grpc/load_reporting.h \ +include/grpc/passive_listener.h \ include/grpc/slice.h \ include/grpc/slice_buffer.h \ include/grpc/status.h \ @@ -1039,6 +1041,7 @@ include/grpcpp/impl/server_initializer.h \ include/grpcpp/impl/service_type.h \ include/grpcpp/impl/status.h \ include/grpcpp/impl/sync.h \ +include/grpcpp/passive_listener.h \ include/grpcpp/resource_quota.h \ include/grpcpp/security/audit_logging.h \ include/grpcpp/security/auth_context.h \ diff --git a/tools/doxygen/Doxyfile.c++.internal b/tools/doxygen/Doxyfile.c++.internal index 68ce1dc0369..b2b6d5cf0f8 100644 --- a/tools/doxygen/Doxyfile.c++.internal +++ b/tools/doxygen/Doxyfile.c++.internal @@ -880,6 +880,7 @@ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/census.h \ include/grpc/compression.h \ +include/grpc/credentials.h \ include/grpc/event_engine/endpoint_config.h \ include/grpc/event_engine/event_engine.h \ include/grpc/event_engine/extensible.h \ @@ -927,6 +928,7 @@ include/grpc/impl/grpc_types.h \ include/grpc/impl/propagation_bits.h \ include/grpc/impl/slice_type.h \ include/grpc/load_reporting.h \ +include/grpc/passive_listener.h \ include/grpc/slice.h \ include/grpc/slice_buffer.h \ include/grpc/status.h \ @@ -1039,6 +1041,7 @@ include/grpcpp/impl/server_initializer.h \ include/grpcpp/impl/service_type.h \ include/grpcpp/impl/status.h \ include/grpcpp/impl/sync.h \ +include/grpcpp/passive_listener.h \ include/grpcpp/resource_quota.h \ include/grpcpp/security/audit_logging.h \ include/grpcpp/security/auth_context.h \ diff --git a/tools/doxygen/Doxyfile.core b/tools/doxygen/Doxyfile.core index f9261a2a94f..42c1ae40ce8 100644 --- a/tools/doxygen/Doxyfile.core +++ b/tools/doxygen/Doxyfile.core @@ -813,6 +813,7 @@ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/census.h \ include/grpc/compression.h \ +include/grpc/credentials.h \ include/grpc/event_engine/endpoint_config.h \ include/grpc/event_engine/event_engine.h \ include/grpc/event_engine/extensible.h \ @@ -860,6 +861,7 @@ include/grpc/impl/grpc_types.h \ include/grpc/impl/propagation_bits.h \ include/grpc/impl/slice_type.h \ include/grpc/load_reporting.h \ +include/grpc/passive_listener.h \ include/grpc/slice.h \ include/grpc/slice_buffer.h \ include/grpc/status.h \ diff --git a/tools/doxygen/Doxyfile.core.internal b/tools/doxygen/Doxyfile.core.internal index 66d40b201af..e9a74dd745e 100644 --- a/tools/doxygen/Doxyfile.core.internal +++ b/tools/doxygen/Doxyfile.core.internal @@ -813,6 +813,7 @@ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/census.h \ include/grpc/compression.h \ +include/grpc/credentials.h \ include/grpc/event_engine/endpoint_config.h \ include/grpc/event_engine/event_engine.h \ include/grpc/event_engine/extensible.h \ @@ -860,6 +861,7 @@ include/grpc/impl/grpc_types.h \ include/grpc/impl/propagation_bits.h \ include/grpc/impl/slice_type.h \ include/grpc/load_reporting.h \ +include/grpc/passive_listener.h \ include/grpc/slice.h \ include/grpc/slice_buffer.h \ include/grpc/status.h \