Compare commits

...

5 Commits

Author SHA1 Message Date
Hannah Shi c650250e9a bump ios.deployment_target to 12.0 for C++17 2025-03-04 11:04:37 -08:00
Hannah Shi 8fec212855 Sync c-core 1.70.1-pre3 2025-03-04 11:04:37 -08:00
Hannah Shi 1c00c39bb3 bump ios.deployment_target to 12.0 for C++17 2025-02-26 10:36:59 -08:00
Hannah Shi 4469511bae upgrade swift package c++ standard to 17 2025-02-26 09:01:37 -08:00
Hannah Shi 83f9e5678f Sync c-core 1.70.1-pre2 2025-02-26 09:01:37 -08:00
556 changed files with 9116 additions and 7290 deletions

View File

@ -111,5 +111,5 @@ let package = Package(
), ),
], ],
cLanguageStandard: .gnu11, cLanguageStandard: .gnu11,
cxxLanguageStandard: .cxx14 cxxLanguageStandard: .cxx17
) )

View File

@ -22,7 +22,7 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = 'gRPC-C++' s.name = 'gRPC-C++'
# TODO (mxyan): use version that match gRPC version when pod is stabilized # TODO (mxyan): use version that match gRPC version when pod is stabilized
version = '1.70.0-dev' version = '1.71.0-pre3'
s.version = version s.version = version
s.summary = 'gRPC C++ library' s.summary = 'gRPC C++ library'
s.homepage = 'https://grpc.io' s.homepage = 'https://grpc.io'
@ -34,7 +34,7 @@ Pod::Spec.new do |s|
:tag => "v#{version}", :tag => "v#{version}",
} }
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'
@ -181,6 +181,8 @@ Pod::Spec.new do |s|
'include/grpcpp/impl/status.h', 'include/grpcpp/impl/status.h',
'include/grpcpp/impl/sync.h', 'include/grpcpp/impl/sync.h',
'include/grpcpp/passive_listener.h', 'include/grpcpp/passive_listener.h',
'include/grpcpp/ports_def.inc',
'include/grpcpp/ports_undef.inc',
'include/grpcpp/resource_quota.h', 'include/grpcpp/resource_quota.h',
'include/grpcpp/security/audit_logging.h', 'include/grpcpp/security/audit_logging.h',
'include/grpcpp/security/auth_context.h', 'include/grpcpp/security/auth_context.h',
@ -267,7 +269,6 @@ Pod::Spec.new do |s|
ss.dependency 'abseil/time/time', abseil_version ss.dependency 'abseil/time/time', abseil_version
ss.dependency 'abseil/types/optional', abseil_version ss.dependency 'abseil/types/optional', abseil_version
ss.dependency 'abseil/types/span', abseil_version ss.dependency 'abseil/types/span', abseil_version
ss.dependency 'abseil/types/variant', abseil_version
ss.dependency 'abseil/utility/utility', abseil_version ss.dependency 'abseil/utility/utility', abseil_version
ss.source_files = 'src/core/call/request_buffer.h', ss.source_files = 'src/core/call/request_buffer.h',
@ -538,6 +539,8 @@ Pod::Spec.new do |s|
'src/core/ext/upb-gen/envoy/type/http/v3/cookie.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/http/v3/cookie.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/http_inputs.upb.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/http_inputs.upb.h',
@ -773,6 +776,7 @@ Pod::Spec.new do |s|
'src/core/ext/upbdefs-gen/envoy/service/status/v3/csds.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/service/status/v3/csds.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/address.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/metadata.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/metadata.upbdefs.h',
@ -1309,6 +1313,7 @@ Pod::Spec.new do |s|
'src/core/util/useful.h', 'src/core/util/useful.h',
'src/core/util/uuid_v4.h', 'src/core/util/uuid_v4.h',
'src/core/util/validation_errors.h', 'src/core/util/validation_errors.h',
'src/core/util/wait_for_single_owner.h',
'src/core/util/work_serializer.h', 'src/core/util/work_serializer.h',
'src/core/util/xxhash_inline.h', 'src/core/util/xxhash_inline.h',
'src/core/xds/grpc/certificate_provider_store.h', 'src/core/xds/grpc/certificate_provider_store.h',
@ -1341,6 +1346,7 @@ Pod::Spec.new do |s|
'src/core/xds/grpc/xds_route_config_parser.h', 'src/core/xds/grpc/xds_route_config_parser.h',
'src/core/xds/grpc/xds_routing.h', 'src/core/xds/grpc/xds_routing.h',
'src/core/xds/grpc/xds_server_grpc.h', 'src/core/xds/grpc/xds_server_grpc.h',
'src/core/xds/grpc/xds_server_grpc_interface.h',
'src/core/xds/grpc/xds_transport_grpc.h', 'src/core/xds/grpc/xds_transport_grpc.h',
'src/core/xds/xds_client/lrs_client.h', 'src/core/xds/xds_client/lrs_client.h',
'src/core/xds/xds_client/xds_api.h', 'src/core/xds/xds_client/xds_api.h',
@ -1834,6 +1840,8 @@ Pod::Spec.new do |s|
'src/core/ext/upb-gen/envoy/type/http/v3/cookie.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/http/v3/cookie.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/http_inputs.upb.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/http_inputs.upb.h',
@ -2069,6 +2077,7 @@ Pod::Spec.new do |s|
'src/core/ext/upbdefs-gen/envoy/service/status/v3/csds.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/service/status/v3/csds.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/address.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/metadata.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/metadata.upbdefs.h',
@ -2605,6 +2614,7 @@ Pod::Spec.new do |s|
'src/core/util/useful.h', 'src/core/util/useful.h',
'src/core/util/uuid_v4.h', 'src/core/util/uuid_v4.h',
'src/core/util/validation_errors.h', 'src/core/util/validation_errors.h',
'src/core/util/wait_for_single_owner.h',
'src/core/util/work_serializer.h', 'src/core/util/work_serializer.h',
'src/core/util/xxhash_inline.h', 'src/core/util/xxhash_inline.h',
'src/core/xds/grpc/certificate_provider_store.h', 'src/core/xds/grpc/certificate_provider_store.h',
@ -2637,6 +2647,7 @@ Pod::Spec.new do |s|
'src/core/xds/grpc/xds_route_config_parser.h', 'src/core/xds/grpc/xds_route_config_parser.h',
'src/core/xds/grpc/xds_routing.h', 'src/core/xds/grpc/xds_routing.h',
'src/core/xds/grpc/xds_server_grpc.h', 'src/core/xds/grpc/xds_server_grpc.h',
'src/core/xds/grpc/xds_server_grpc_interface.h',
'src/core/xds/grpc/xds_transport_grpc.h', 'src/core/xds/grpc/xds_transport_grpc.h',
'src/core/xds/xds_client/lrs_client.h', 'src/core/xds/xds_client/lrs_client.h',
'src/core/xds/xds_client/xds_api.h', 'src/core/xds/xds_client/xds_api.h',

View File

@ -21,7 +21,7 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = 'gRPC-Core' s.name = 'gRPC-Core'
version = '1.70.0-dev' version = '1.71.0-pre3'
s.version = version s.version = version
s.summary = 'Core cross-platform gRPC library, written in C' s.summary = 'Core cross-platform gRPC library, written in C'
s.homepage = 'https://grpc.io' s.homepage = 'https://grpc.io'
@ -38,7 +38,7 @@ Pod::Spec.new do |s|
# which was released in Cocoapods v1.2.0. # which was released in Cocoapods v1.2.0.
s.cocoapods_version = '>= 1.2.0' s.cocoapods_version = '>= 1.2.0'
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'
@ -200,7 +200,7 @@ Pod::Spec.new do |s|
ss.libraries = 'z' ss.libraries = 'z'
ss.dependency "#{s.name}/Interface", version ss.dependency "#{s.name}/Interface", version
ss.dependency "#{s.name}/Privacy", version ss.dependency "#{s.name}/Privacy", version
ss.dependency 'BoringSSL-GRPC', '0.0.38' ss.dependency 'BoringSSL-GRPC', '0.0.39'
ss.dependency 'abseil/algorithm/container', abseil_version ss.dependency 'abseil/algorithm/container', abseil_version
ss.dependency 'abseil/base/base', abseil_version ss.dependency 'abseil/base/base', abseil_version
ss.dependency 'abseil/base/config', abseil_version ss.dependency 'abseil/base/config', abseil_version
@ -235,7 +235,6 @@ Pod::Spec.new do |s|
ss.dependency 'abseil/time/time', abseil_version ss.dependency 'abseil/time/time', abseil_version
ss.dependency 'abseil/types/optional', abseil_version ss.dependency 'abseil/types/optional', abseil_version
ss.dependency 'abseil/types/span', abseil_version ss.dependency 'abseil/types/span', abseil_version
ss.dependency 'abseil/types/variant', abseil_version
ss.dependency 'abseil/utility/utility', abseil_version ss.dependency 'abseil/utility/utility', abseil_version
ss.compiler_flags = '-DBORINGSSL_PREFIX=GRPC -Wno-unreachable-code -Wno-shorten-64-to-32' ss.compiler_flags = '-DBORINGSSL_PREFIX=GRPC -Wno-unreachable-code -Wno-shorten-64-to-32'
@ -679,6 +678,9 @@ Pod::Spec.new do |s|
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.c', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.c',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb_minitable.c',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.c', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.c',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h',
@ -1075,6 +1077,8 @@ Pod::Spec.new do |s|
'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.c', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.c',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/address.upbdefs.c',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/address.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.c', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.c',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.c', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.c',
@ -2092,6 +2096,7 @@ Pod::Spec.new do |s|
'src/core/util/uuid_v4.h', 'src/core/util/uuid_v4.h',
'src/core/util/validation_errors.cc', 'src/core/util/validation_errors.cc',
'src/core/util/validation_errors.h', 'src/core/util/validation_errors.h',
'src/core/util/wait_for_single_owner.h',
'src/core/util/windows/cpu.cc', 'src/core/util/windows/cpu.cc',
'src/core/util/windows/directory_reader.cc', 'src/core/util/windows/directory_reader.cc',
'src/core/util/windows/env.cc', 'src/core/util/windows/env.cc',
@ -2162,6 +2167,7 @@ Pod::Spec.new do |s|
'src/core/xds/grpc/xds_routing.h', 'src/core/xds/grpc/xds_routing.h',
'src/core/xds/grpc/xds_server_grpc.cc', 'src/core/xds/grpc/xds_server_grpc.cc',
'src/core/xds/grpc/xds_server_grpc.h', 'src/core/xds/grpc/xds_server_grpc.h',
'src/core/xds/grpc/xds_server_grpc_interface.h',
'src/core/xds/grpc/xds_transport_grpc.cc', 'src/core/xds/grpc/xds_transport_grpc.cc',
'src/core/xds/grpc/xds_transport_grpc.h', 'src/core/xds/grpc/xds_transport_grpc.h',
'src/core/xds/xds_client/lrs_client.cc', 'src/core/xds/xds_client/lrs_client.cc',
@ -2689,6 +2695,8 @@ Pod::Spec.new do |s|
'src/core/ext/upb-gen/envoy/type/http/v3/cookie.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/http/v3/cookie.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb.h',
'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/http/v3/path_transformation.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/address.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/filter_state.upb_minitable.h',
'src/core/ext/upb-gen/envoy/type/matcher/v3/http_inputs.upb.h', 'src/core/ext/upb-gen/envoy/type/matcher/v3/http_inputs.upb.h',
@ -2924,6 +2932,7 @@ Pod::Spec.new do |s|
'src/core/ext/upbdefs-gen/envoy/service/status/v3/csds.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/service/status/v3/csds.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/cookie.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/http/v3/path_transformation.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/address.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/filter_state.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/http_inputs.upbdefs.h',
'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/metadata.upbdefs.h', 'src/core/ext/upbdefs-gen/envoy/type/matcher/v3/metadata.upbdefs.h',
@ -3460,6 +3469,7 @@ Pod::Spec.new do |s|
'src/core/util/useful.h', 'src/core/util/useful.h',
'src/core/util/uuid_v4.h', 'src/core/util/uuid_v4.h',
'src/core/util/validation_errors.h', 'src/core/util/validation_errors.h',
'src/core/util/wait_for_single_owner.h',
'src/core/util/work_serializer.h', 'src/core/util/work_serializer.h',
'src/core/util/xxhash_inline.h', 'src/core/util/xxhash_inline.h',
'src/core/xds/grpc/certificate_provider_store.h', 'src/core/xds/grpc/certificate_provider_store.h',
@ -3491,6 +3501,7 @@ Pod::Spec.new do |s|
'src/core/xds/grpc/xds_route_config_parser.h', 'src/core/xds/grpc/xds_route_config_parser.h',
'src/core/xds/grpc/xds_routing.h', 'src/core/xds/grpc/xds_routing.h',
'src/core/xds/grpc/xds_server_grpc.h', 'src/core/xds/grpc/xds_server_grpc.h',
'src/core/xds/grpc/xds_server_grpc_interface.h',
'src/core/xds/grpc/xds_transport_grpc.h', 'src/core/xds/grpc/xds_transport_grpc.h',
'src/core/xds/xds_client/lrs_client.h', 'src/core/xds/xds_client/lrs_client.h',
'src/core/xds/xds_client/xds_api.h', 'src/core/xds/xds_client/xds_api.h',

View File

@ -21,7 +21,7 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = 'gRPC-ProtoRPC' s.name = 'gRPC-ProtoRPC'
version = '1.70.0-dev' version = '1.71.0-pre3'
s.version = version s.version = version
s.summary = 'RPC library for Protocol Buffers, based on gRPC' s.summary = 'RPC library for Protocol Buffers, based on gRPC'
s.homepage = 'https://grpc.io' s.homepage = 'https://grpc.io'
@ -33,7 +33,7 @@ Pod::Spec.new do |s|
:tag => "v#{version}", :tag => "v#{version}",
} }
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'

View File

@ -21,7 +21,7 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = 'gRPC-RxLibrary' s.name = 'gRPC-RxLibrary'
version = '1.70.0-dev' version = '1.71.0-pre3'
s.version = version s.version = version
s.summary = 'Reactive Extensions library for iOS/OSX.' s.summary = 'Reactive Extensions library for iOS/OSX.'
s.homepage = 'https://grpc.io' s.homepage = 'https://grpc.io'
@ -33,7 +33,7 @@ Pod::Spec.new do |s|
:tag => "v#{version}", :tag => "v#{version}",
} }
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'

View File

@ -20,7 +20,7 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = 'gRPC' s.name = 'gRPC'
version = '1.70.0-dev' version = '1.71.0-pre3'
s.version = version s.version = version
s.summary = 'gRPC client library for iOS/OSX' s.summary = 'gRPC client library for iOS/OSX'
s.homepage = 'https://grpc.io' s.homepage = 'https://grpc.io'
@ -45,7 +45,7 @@ Pod::Spec.new do |s|
'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17',
} }
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'
@ -80,7 +80,7 @@ Pod::Spec.new do |s|
"src/objective-c/GRPCClient/GRPCTypes.mm" "src/objective-c/GRPCClient/GRPCTypes.mm"
ss.dependency "gRPC-RxLibrary/Interface", version ss.dependency "gRPC-RxLibrary/Interface", version
ss.dependency "#{s.name}/Privacy", version ss.dependency "#{s.name}/Privacy", version
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'
@ -116,7 +116,7 @@ Pod::Spec.new do |s|
ss.dependency "#{s.name}/Interface-Legacy", version ss.dependency "#{s.name}/Interface-Legacy", version
ss.dependency "#{s.name}/Privacy", version ss.dependency "#{s.name}/Privacy", version
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'
@ -154,7 +154,7 @@ Pod::Spec.new do |s|
ss.dependency 'gRPC-Core', version ss.dependency 'gRPC-Core', version
ss.dependency 'gRPC-RxLibrary', version ss.dependency 'gRPC-RxLibrary', version
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'
@ -172,14 +172,14 @@ Pod::Spec.new do |s|
ss.dependency 'gRPC-Core/Cronet-Implementation', version ss.dependency 'gRPC-Core/Cronet-Implementation', version
ss.dependency 'CronetFramework' ss.dependency 'CronetFramework'
ss.ios.deployment_target = '11.0' ss.ios.deployment_target = '12.0'
end end
# CFStream is now default. Leaving this subspec only for compatibility purpose. # CFStream is now default. Leaving this subspec only for compatibility purpose.
s.subspec 'CFStream' do |ss| s.subspec 'CFStream' do |ss|
ss.dependency "#{s.name}/GRPCCore", version ss.dependency "#{s.name}/GRPCCore", version
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'
@ -192,7 +192,7 @@ Pod::Spec.new do |s|
ss.source_files = 'src/objective-c/GRPCClient/internal_testing/*.{h,mm}' ss.source_files = 'src/objective-c/GRPCClient/internal_testing/*.{h,mm}'
ss.header_mappings_dir = 'src/objective-c/GRPCClient' ss.header_mappings_dir = 'src/objective-c/GRPCClient'
s.ios.deployment_target = '11.0' s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14' s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '13.0' s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0' s.watchos.deployment_target = '6.0'

View File

@ -16,10 +16,10 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <optional>
#include <string> #include <string>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace grpc_event_engine { namespace grpc_event_engine {
namespace experimental { namespace experimental {
@ -32,11 +32,11 @@ class EndpointConfig {
public: public:
virtual ~EndpointConfig() = default; virtual ~EndpointConfig() = default;
// If the key points to an integer config, an integer value gets returned. // If the key points to an integer config, an integer value gets returned.
// Otherwise it returns an absl::nullopt_t // Otherwise it returns an std::nullopt_t
virtual absl::optional<int> GetInt(absl::string_view key) const = 0; virtual std::optional<int> GetInt(absl::string_view key) const = 0;
// If the key points to an string config, an string value gets returned. // If the key points to an string config, an string value gets returned.
// Otherwise it returns an absl::nullopt_t // Otherwise it returns an std::nullopt_t
virtual absl::optional<absl::string_view> GetString( virtual std::optional<absl::string_view> GetString(
absl::string_view key) const = 0; absl::string_view key) const = 0;
// If the key points to an void* config, a void* pointer value gets returned. // If the key points to an void* config, a void* pointer value gets returned.
// Otherwise it returns nullptr // Otherwise it returns nullptr

View File

@ -28,6 +28,7 @@
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
// TODO(vigneshbabu): Define the Endpoint::Write metrics collection system // TODO(vigneshbabu): Define the Endpoint::Write metrics collection system
// TODO(hork): remove all references to the factory methods.
namespace grpc_event_engine { namespace grpc_event_engine {
namespace experimental { namespace experimental {
@ -471,7 +472,7 @@ class EventEngine : public std::enable_shared_from_this<EventEngine>,
virtual bool Cancel(TaskHandle handle) = 0; virtual bool Cancel(TaskHandle handle) = 0;
}; };
/// Replace gRPC's default EventEngine factory. /// [DEPRECATED] Replace gRPC's default EventEngine factory.
/// ///
/// Applications may call \a SetEventEngineFactory at any time to replace the /// Applications may call \a SetEventEngineFactory at any time to replace the
/// default factory used within gRPC. EventEngines will be created when /// default factory used within gRPC. EventEngines will be created when
@ -480,18 +481,56 @@ class EventEngine : public std::enable_shared_from_this<EventEngine>,
/// To be certain that none of the gRPC-provided built-in EventEngines are /// To be certain that none of the gRPC-provided built-in EventEngines are
/// created, applications must set a custom EventEngine factory method *before* /// created, applications must set a custom EventEngine factory method *before*
/// grpc is initialized. /// grpc is initialized.
// TODO(hork): delete once all known users have migrated away
void SetEventEngineFactory( void SetEventEngineFactory(
absl::AnyInvocable<std::unique_ptr<EventEngine>()> factory); absl::AnyInvocable<std::shared_ptr<EventEngine>()> factory);
/// Reset gRPC's EventEngine factory to the built-in default. /// [DEPRECATED] Reset gRPC's EventEngine factory to the built-in default.
/// ///
/// Applications that have called \a SetEventEngineFactory can remove their /// Applications that have called \a SetEventEngineFactory can remove their
/// custom factory using this method. The built-in EventEngine factories will be /// custom factory using this method. The built-in EventEngine factories will be
/// used going forward. This has no affect on any EventEngines that were created /// used going forward. This has no affect on any EventEngines that were created
/// using the previous factories. /// using the previous factories.
//
// TODO(hork): delete once all known users have migrated away
void EventEngineFactoryReset(); void EventEngineFactoryReset();
/// Create an EventEngine using the default factory.
std::unique_ptr<EventEngine> CreateEventEngine(); /// Create a new EventEngine instance.
std::shared_ptr<EventEngine> CreateEventEngine();
/// Set the default EventEngine instance, which will be used throughout gRPC
///
/// gRPC will hold a ref to this engine until either
/// \a ShutdownDefaultEventEngine() is called or \a SetDefaultEventEngine() is
/// called again with a different value. Passing a value of nullptr will cause
/// gRPC to drop the ref it was holding without setting it to a new one.
///
/// Earlier calls to \a GetDefaultEventEngine will still hold a ref to the
/// previous default engine instance, if any.
void SetDefaultEventEngine(std::shared_ptr<EventEngine> engine);
/// Returns the default EventEngine instance.
///
/// Note that if SetDefaultEventEngine() has not been called, then the default
/// EventEngine may be created and destroyed as needed, meaning that multiple
/// calls to GetDefaultEventEngine() over a process's lifetime may return
/// different instances. Callers are expected to call GetDefaultEventEngine()
/// once and hold the returned reference for as long as they need the
/// EventEngine instance.
std::shared_ptr<EventEngine> GetDefaultEventEngine();
/// Resets gRPC to use one of the default internal EventEngines for all *new*
/// \a GetDefaultEventEngine requests and blocks until all refs on the active
/// default engine have been released (destroying that engine).
///
/// If you called \a SetDefaultEventEngine, you must call either
/// \a ShutdownDefaultEventEngine or \a SetDefaultEventEngine(nullptr) at the
/// end of your program. If you don't, the engine will never be destroyed.
///
/// If you want to reset the default engine to one of gRPC's internal versions
/// without waiting for all references to be released on the current default
/// engine, call \a SetDefaultEventEngine(nullptr) instead.
void ShutdownDefaultEventEngine();
bool operator==(const EventEngine::TaskHandle& lhs, bool operator==(const EventEngine::TaskHandle& lhs,
const EventEngine::TaskHandle& rhs); const EventEngine::TaskHandle& rhs);

View File

@ -146,7 +146,7 @@ typedef enum {
GRPC_STATUS_DATA_LOSS = 15, GRPC_STATUS_DATA_LOSS = 15,
/** Force users to include a default branch: */ /** Force users to include a default branch: */
GRPC_STATUS__DO_NOT_USE = -1 GRPC_STATUS__DO_NOT_USE = 0x7fffffffu,
} grpc_status_code; } grpc_status_code;
#ifdef __cplusplus #ifdef __cplusplus

View File

@ -23,10 +23,10 @@
#include <map> #include <map>
#include <string> #include <string>
#include <utility> #include <utility>
#include <variant>
#include <vector> #include <vector>
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/types/variant.h"
namespace grpc_core { namespace grpc_core {
namespace experimental { namespace experimental {
@ -147,46 +147,46 @@ class Json {
// Moveable. // Moveable.
Json(Json&& other) noexcept : value_(std::move(other.value_)) { Json(Json&& other) noexcept : value_(std::move(other.value_)) {
other.value_ = absl::monostate(); other.value_ = std::monostate();
} }
Json& operator=(Json&& other) noexcept { Json& operator=(Json&& other) noexcept {
value_ = std::move(other.value_); value_ = std::move(other.value_);
other.value_ = absl::monostate(); other.value_ = std::monostate();
return *this; return *this;
} }
// Returns the JSON type. // Returns the JSON type.
Type type() const { Type type() const {
struct ValueFunctor { struct ValueFunctor {
Json::Type operator()(const absl::monostate&) { return Type::kNull; } Json::Type operator()(const std::monostate&) { return Type::kNull; }
Json::Type operator()(bool) { return Type::kBoolean; } Json::Type operator()(bool) { return Type::kBoolean; }
Json::Type operator()(const NumberValue&) { return Type::kNumber; } Json::Type operator()(const NumberValue&) { return Type::kNumber; }
Json::Type operator()(const std::string&) { return Type::kString; } Json::Type operator()(const std::string&) { return Type::kString; }
Json::Type operator()(const Object&) { return Type::kObject; } Json::Type operator()(const Object&) { return Type::kObject; }
Json::Type operator()(const Array&) { return Type::kArray; } Json::Type operator()(const Array&) { return Type::kArray; }
}; };
return absl::visit(ValueFunctor(), value_); return std::visit(ValueFunctor(), value_);
} }
// Payload accessor for kBoolean. // Payload accessor for kBoolean.
// Must not be called for other types. // Must not be called for other types.
bool boolean() const { return absl::get<bool>(value_); } bool boolean() const { return std::get<bool>(value_); }
// Payload accessor for kNumber or kString. // Payload accessor for kNumber or kString.
// Must not be called for other types. // Must not be called for other types.
const std::string& string() const { const std::string& string() const {
const NumberValue* num = absl::get_if<NumberValue>(&value_); const NumberValue* num = std::get_if<NumberValue>(&value_);
if (num != nullptr) return num->value; if (num != nullptr) return num->value;
return absl::get<std::string>(value_); return std::get<std::string>(value_);
} }
// Payload accessor for kObject. // Payload accessor for kObject.
// Must not be called for other types. // Must not be called for other types.
const Object& object() const { return absl::get<Object>(value_); } const Object& object() const { return std::get<Object>(value_); }
// Payload accessor for kArray. // Payload accessor for kArray.
// Must not be called for other types. // Must not be called for other types.
const Array& array() const { return absl::get<Array>(value_); } const Array& array() const { return std::get<Array>(value_); }
bool operator==(const Json& other) const { return value_ == other.value_; } bool operator==(const Json& other) const { return value_ == other.value_; }
bool operator!=(const Json& other) const { return !(*this == other); } bool operator!=(const Json& other) const { return !(*this == other); }
@ -199,7 +199,7 @@ class Json {
return value == other.value; return value == other.value;
} }
}; };
using Value = absl::variant<absl::monostate, // kNull using Value = std::variant<std::monostate, // kNull
bool, // kBoolean bool, // kBoolean
NumberValue, // kNumber NumberValue, // kNumber
std::string, // kString std::string, // kString

View File

@ -26,7 +26,6 @@
#include <string> #include <string>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace grpc { namespace grpc {
namespace experimental { namespace experimental {

View File

@ -0,0 +1,137 @@
/*
*
* Copyright 2025 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.
*
* Protect Code from unwanted/inconvienet macros
* you must follow this pattern when #including port_def.inc in a header file:
*
* #include "other_header.h"
* #include "message.h"
* etc.
*
* #include "port_def.inc" // MUST be last header included
*
* Definitions for this header.
*
* #include "port_undef.inc" //At end of file
*
* This is a textual header with no include guard, because we want to
* detect/prohibit anytime it is #included twice without a corresponding
* #undef.
*/
#ifdef GRPC_PORT_
#error "port_def.inc included multiple times"
#endif
#define GRPC_PORT_
// Windows declares several inconvenient macro names. We #undef them and then
// restore them in port_undef.inc.
#ifdef _WIN32
#pragma push_macro("CompareString")
#undef CompareString
#pragma push_macro("CREATE_NEW")
#undef CREATE_NEW
#pragma push_macro("DELETE")
#undef DELETE
#pragma push_macro("DOUBLE_CLICK")
#undef DOUBLE_CLICK
#pragma push_macro("ERROR")
#undef ERROR
#pragma push_macro("ERROR_BUSY")
#undef ERROR_BUSY
#pragma push_macro("ERROR_INSTALL_FAILED")
#undef ERROR_INSTALL_FAILED
#pragma push_macro("ERROR_NOT_FOUND")
#undef ERROR_NOT_FOUND
#pragma push_macro("ERROR_RETRY")
#undef ERROR_RETRY
#pragma push_macro("ERROR_TIMEOUT")
#undef ERROR_TIMEOUT
#pragma push_macro("GetClassName")
#undef GetClassName
#pragma push_macro("GetCurrentTime")
#undef GetCurrentTime
#pragma push_macro("GetMessage")
#undef GetMessage
#pragma push_macro("GetObject")
#undef GetObject
#pragma push_macro("IGNORE")
#undef IGNORE
#pragma push_macro("IN")
#undef IN
#pragma push_macro("INPUT_KEYBOARD")
#undef INPUT_KEYBOARD
#pragma push_macro("NO_ERROR")
#undef NO_ERROR
#pragma push_macro("OUT")
#undef OUT
#pragma push_macro("OPTIONAL")
#undef OPTIONAL
#pragma push_macro("min")
#undef min
#pragma push_macro("max")
#undef max
#pragma push_macro("NEAR")
#undef NEAR
#pragma push_macro("NO_DATA")
#undef NO_DATA
#pragma push_macro("REASON_UNKNOWN")
#undef REASON_UNKNOWN
#pragma push_macro("SERVICE_DISABLED")
#undef SERVICE_DISABLED
#pragma push_macro("SERVICE_STOP")
#undef SERVICE_STOP
#pragma push_macro("SEVERITY_ERROR")
#undef SEVERITY_ERROR
#pragma push_macro("STATUS_PENDING")
#undef STATUS_PENDING
#pragma push_macro("STRICT")
#undef STRICT
#pragma push_macro("timezone")
#undef timezone
#pragma push_macro("TRUE")
#undef TRUE
#pragma push_macro("FALSE")
#undef FALSE
#pragma push_macro("UNICODE")
#undef UNICODE
#endif // _WIN32
#ifdef __APPLE__
// Inconvenient macro names from /usr/include/mach/boolean.h in some macOS SDKs.
#pragma push_macro("TRUE")
#undef TRUE
#pragma push_macro("FALSE")
#undef FALSE
// Inconvenient macro names from usr/include/sys/syslimits.h in some macOS SDKs.
#pragma push_macro("UID_MAX")
#undef UID_MAX
#pragma push_macro("GID_MAX")
#undef GID_MAX
// TYPE_BOOL is defined in the MacOS's ConditionalMacros.h.
#pragma push_macro("TYPE_BOOL")
#undef TYPE_BOOL
#endif // __APPLE__
#if defined(ANDROID) || defined(__ANDROID__)
// Inconvenient macro names from usr/include/limits.h in some Android NDKs.
#pragma push_macro("UID_MAX")
#undef UID_MAX
#pragma push_macro("GID_MAX")
#undef GID_MAX
#endif // defined(ANDROID) || defined(__ANDROID__)

View File

@ -0,0 +1,75 @@
/*
*
* Copyright 2025 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.
*
* #undefs all macros defined in port_def.inc. See comments in port_def.inc
* for more info.
*/
#ifndef GRPC_PORT_
#error "port_undef.inc must be included after port_def.inc"
#endif
#undef GRPC_PORT_
#ifdef _WIN32
#pragma pop_macro("CompareString")
#pragma pop_macro("CREATE_NEW")
#pragma pop_macro("DELETE")
#pragma pop_macro("DOUBLE_CLICK")
#pragma pop_macro("ERROR")
#pragma pop_macro("ERROR_BUSY")
#pragma pop_macro("ERROR_INSTALL_FAILED")
#pragma pop_macro("ERROR_NOT_FOUND")
#pragma pop_macro("ERROR_RETRY")
#pragma pop_macro("ERROR_TIMEOUT")
#pragma pop_macro("GetClassName")
#pragma pop_macro("GetCurrentTime")
#pragma pop_macro("GetMessage")
#pragma pop_macro("GetObject")
#pragma pop_macro("IGNORE")
#pragma pop_macro("IN")
#pragma pop_macro("INPUT_KEYBOARD")
#pragma pop_macro("NO_ERROR")
#pragma pop_macro("OUT")
#pragma pop_macro("OPTIONAL")
#pragma pop_macro("min")
#pragma pop_macro("max")
#pragma pop_macro("NEAR")
#pragma pop_macro("NO_DATA")
#pragma pop_macro("REASON_UNKNOWN")
#pragma pop_macro("SERVICE_DISABLED")
#pragma pop_macro("SERVICE_STOP")
#pragma pop_macro("SEVERITY_ERROR")
#pragma pop_macro("STRICT")
#pragma pop_macro("STATUS_PENDING")
#pragma pop_macro("timezone")
#pragma pop_macro("TRUE")
#pragma pop_macro("FALSE")
#pragma pop_macro("UNICODE")
#endif
#ifdef __APPLE__
#pragma pop_macro("TRUE")
#pragma pop_macro("FALSE")
#pragma pop_macro("UID_MAX")
#pragma pop_macro("GID_MAX")
#pragma pop_macro("TYPE_BOOL")
#endif // __APPLE__
#if defined(ANDROID) || defined(__ANDROID__)
#pragma pop_macro("UID_MAX")
#pragma pop_macro("GID_MAX")
#endif // defined(ANDROID) || defined(__ANDROID__)

View File

@ -477,10 +477,10 @@ class ServerBidiReactor : public internal::ServerReactor {
} }
grpc::internal::Mutex stream_mu_; grpc::internal::Mutex stream_mu_;
// TODO(vjpai): Make stream_or_backlog_ into a std::variant or absl::variant // TODO(vjpai): Make stream_or_backlog_ into an std::variant once C++17 or
// once C++17 or ABSL is supported since stream and backlog are // ABSL is supported since stream and backlog are mutually exclusive in this
// mutually exclusive in this class. Do likewise with the // class. Do likewise with the remaining reactor classes and their backlogs
// remaining reactor classes and their backlogs as well. // as well.
std::atomic<ServerCallbackReaderWriter<Request, Response>*> stream_{nullptr}; std::atomic<ServerCallbackReaderWriter<Request, Response>*> stream_{nullptr};
struct PreBindBacklog { struct PreBindBacklog {
bool send_initial_metadata_wanted = false; bool send_initial_metadata_wanted = false;

View File

@ -19,9 +19,9 @@
#define GRPCPP_VERSION_INFO_H #define GRPCPP_VERSION_INFO_H
#define GRPC_CPP_VERSION_MAJOR 1 #define GRPC_CPP_VERSION_MAJOR 1
#define GRPC_CPP_VERSION_MINOR 70 #define GRPC_CPP_VERSION_MINOR 71
#define GRPC_CPP_VERSION_PATCH 0 #define GRPC_CPP_VERSION_PATCH 0
#define GRPC_CPP_VERSION_TAG "dev" #define GRPC_CPP_VERSION_TAG "pre3"
#define GRPC_CPP_VERSION_STRING "1.70.0-dev" #define GRPC_CPP_VERSION_STRING "1.71.0-pre3"
#endif // GRPCPP_VERSION_INFO_H #endif // GRPCPP_VERSION_INFO_H

View File

@ -15,9 +15,9 @@
#include "src/core/call/request_buffer.h" #include "src/core/call/request_buffer.h"
#include <cstdint> #include <cstdint>
#include <optional>
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "src/core/util/match.h" #include "src/core/util/match.h"
namespace grpc_core { namespace grpc_core {
@ -29,8 +29,8 @@ RequestBuffer::RequestBuffer() : state_(absl::in_place_type_t<Buffering>()) {}
ValueOrFailure<size_t> RequestBuffer::PushClientInitialMetadata( ValueOrFailure<size_t> RequestBuffer::PushClientInitialMetadata(
ClientMetadataHandle md) { ClientMetadataHandle md) {
MutexLock lock(&mu_); MutexLock lock(&mu_);
if (absl::get_if<Cancelled>(&state_)) return Failure{}; if (std::get_if<Cancelled>(&state_)) return Failure{};
auto& buffering = absl::get<Buffering>(state_); auto& buffering = std::get<Buffering>(state_);
CHECK_EQ(buffering.initial_metadata.get(), nullptr); CHECK_EQ(buffering.initial_metadata.get(), nullptr);
buffering.initial_metadata = std::move(md); buffering.initial_metadata = std::move(md);
buffering.buffered += buffering.initial_metadata->TransportSize(); buffering.buffered += buffering.initial_metadata->TransportSize();
@ -41,15 +41,15 @@ ValueOrFailure<size_t> RequestBuffer::PushClientInitialMetadata(
Poll<ValueOrFailure<size_t>> RequestBuffer::PollPushMessage( Poll<ValueOrFailure<size_t>> RequestBuffer::PollPushMessage(
MessageHandle& message) { MessageHandle& message) {
MutexLock lock(&mu_); MutexLock lock(&mu_);
if (absl::get_if<Cancelled>(&state_)) return Failure{}; if (std::get_if<Cancelled>(&state_)) return Failure{};
size_t buffered = 0; size_t buffered = 0;
if (auto* buffering = absl::get_if<Buffering>(&state_)) { if (auto* buffering = std::get_if<Buffering>(&state_)) {
if (winner_ != nullptr) return PendingPush(); if (winner_ != nullptr) return PendingPush();
buffering->buffered += message->payload()->Length(); buffering->buffered += message->payload()->Length();
buffered = buffering->buffered; buffered = buffering->buffered;
buffering->messages.push_back(std::move(message)); buffering->messages.push_back(std::move(message));
} else { } else {
auto& streaming = absl::get<Streaming>(state_); auto& streaming = std::get<Streaming>(state_);
CHECK_EQ(streaming.end_of_stream, false); CHECK_EQ(streaming.end_of_stream, false);
if (streaming.message != nullptr) { if (streaming.message != nullptr) {
return PendingPush(); return PendingPush();
@ -62,13 +62,13 @@ Poll<ValueOrFailure<size_t>> RequestBuffer::PollPushMessage(
StatusFlag RequestBuffer::FinishSends() { StatusFlag RequestBuffer::FinishSends() {
MutexLock lock(&mu_); MutexLock lock(&mu_);
if (absl::get_if<Cancelled>(&state_)) return Failure{}; if (std::get_if<Cancelled>(&state_)) return Failure{};
if (auto* buffering = absl::get_if<Buffering>(&state_)) { if (auto* buffering = std::get_if<Buffering>(&state_)) {
Buffered buffered(std::move(buffering->initial_metadata), Buffered buffered(std::move(buffering->initial_metadata),
std::move(buffering->messages)); std::move(buffering->messages));
state_.emplace<Buffered>(std::move(buffered)); state_.emplace<Buffered>(std::move(buffered));
} else { } else {
auto& streaming = absl::get<Streaming>(state_); auto& streaming = std::get<Streaming>(state_);
CHECK_EQ(streaming.end_of_stream, false); CHECK_EQ(streaming.end_of_stream, false);
streaming.end_of_stream = true; streaming.end_of_stream = true;
} }
@ -78,7 +78,7 @@ StatusFlag RequestBuffer::FinishSends() {
void RequestBuffer::Cancel(absl::Status error) { void RequestBuffer::Cancel(absl::Status error) {
MutexLock lock(&mu_); MutexLock lock(&mu_);
if (absl::holds_alternative<Cancelled>(state_)) return; if (std::holds_alternative<Cancelled>(state_)) return;
state_.emplace<Cancelled>(std::move(error)); state_.emplace<Cancelled>(std::move(error));
WakeupAsyncAllPullers(); WakeupAsyncAllPullers();
} }
@ -87,13 +87,13 @@ void RequestBuffer::Commit(Reader* winner) {
MutexLock lock(&mu_); MutexLock lock(&mu_);
CHECK_EQ(winner_, nullptr); CHECK_EQ(winner_, nullptr);
winner_ = winner; winner_ = winner;
if (auto* buffering = absl::get_if<Buffering>(&state_)) { if (auto* buffering = std::get_if<Buffering>(&state_)) {
if (buffering->initial_metadata != nullptr && if (buffering->initial_metadata != nullptr &&
winner->message_index_ == buffering->messages.size() && winner->message_index_ == buffering->messages.size() &&
winner->pulled_client_initial_metadata_) { winner->pulled_client_initial_metadata_) {
state_.emplace<Streaming>(); state_.emplace<Streaming>();
} }
} else if (auto* buffered = absl::get_if<Buffered>(&state_)) { } else if (auto* buffered = std::get_if<Buffered>(&state_)) {
CHECK_NE(buffered->initial_metadata.get(), nullptr); CHECK_NE(buffered->initial_metadata.get(), nullptr);
if (winner->message_index_ == buffered->messages.size()) { if (winner->message_index_ == buffered->messages.size()) {
state_.emplace<Streaming>().end_of_stream = true; state_.emplace<Streaming>().end_of_stream = true;
@ -116,7 +116,7 @@ RequestBuffer::Reader::PollPullClientInitialMetadata() {
error_ = absl::CancelledError("Another call was chosen"); error_ = absl::CancelledError("Another call was chosen");
return Failure{}; return Failure{};
} }
if (auto* buffering = absl::get_if<Buffering>(&buffer_->state_)) { if (auto* buffering = std::get_if<Buffering>(&buffer_->state_)) {
if (buffering->initial_metadata.get() == nullptr) { if (buffering->initial_metadata.get() == nullptr) {
return buffer_->PendingPull(this); return buffer_->PendingPull(this);
} }
@ -125,22 +125,22 @@ RequestBuffer::Reader::PollPullClientInitialMetadata() {
buffer_->MaybeSwitchToStreaming(); buffer_->MaybeSwitchToStreaming();
return std::move(result); return std::move(result);
} }
if (auto* buffered = absl::get_if<Buffered>(&buffer_->state_)) { if (auto* buffered = std::get_if<Buffered>(&buffer_->state_)) {
pulled_client_initial_metadata_ = true; pulled_client_initial_metadata_ = true;
return ClaimObject(buffered->initial_metadata); return ClaimObject(buffered->initial_metadata);
} }
error_ = absl::get<Cancelled>(buffer_->state_).error; error_ = std::get<Cancelled>(buffer_->state_).error;
return Failure{}; return Failure{};
} }
Poll<ValueOrFailure<absl::optional<MessageHandle>>> Poll<ValueOrFailure<std::optional<MessageHandle>>>
RequestBuffer::Reader::PollPullMessage() { RequestBuffer::Reader::PollPullMessage() {
ReleasableMutexLock lock(&buffer_->mu_); ReleasableMutexLock lock(&buffer_->mu_);
if (buffer_->winner_ != nullptr && buffer_->winner_ != this) { if (buffer_->winner_ != nullptr && buffer_->winner_ != this) {
error_ = absl::CancelledError("Another call was chosen"); error_ = absl::CancelledError("Another call was chosen");
return Failure{}; return Failure{};
} }
if (auto* buffering = absl::get_if<Buffering>(&buffer_->state_)) { if (auto* buffering = std::get_if<Buffering>(&buffer_->state_)) {
if (message_index_ == buffering->messages.size()) { if (message_index_ == buffering->messages.size()) {
return buffer_->PendingPull(this); return buffer_->PendingPull(this);
} }
@ -150,15 +150,15 @@ RequestBuffer::Reader::PollPullMessage() {
buffer_->MaybeSwitchToStreaming(); buffer_->MaybeSwitchToStreaming();
return std::move(result); return std::move(result);
} }
if (auto* buffered = absl::get_if<Buffered>(&buffer_->state_)) { if (auto* buffered = std::get_if<Buffered>(&buffer_->state_)) {
if (message_index_ == buffered->messages.size()) return absl::nullopt; if (message_index_ == buffered->messages.size()) return std::nullopt;
const auto idx = message_index_; const auto idx = message_index_;
++message_index_; ++message_index_;
return ClaimObject(buffered->messages[idx]); return ClaimObject(buffered->messages[idx]);
} }
if (auto* streaming = absl::get_if<Streaming>(&buffer_->state_)) { if (auto* streaming = std::get_if<Streaming>(&buffer_->state_)) {
if (streaming->message == nullptr) { if (streaming->message == nullptr) {
if (streaming->end_of_stream) return absl::nullopt; if (streaming->end_of_stream) return std::nullopt;
return buffer_->PendingPull(this); return buffer_->PendingPull(this);
} }
auto msg = std::move(streaming->message); auto msg = std::move(streaming->message);
@ -167,7 +167,7 @@ RequestBuffer::Reader::PollPullMessage() {
waker.Wakeup(); waker.Wakeup();
return std::move(msg); return std::move(msg);
} }
error_ = absl::get<Cancelled>(buffer_->state_).error; error_ = std::get<Cancelled>(buffer_->state_).error;
return Failure{}; return Failure{};
} }

View File

@ -51,7 +51,7 @@ class RequestBuffer {
return [this]() { return PollPullClientInitialMetadata(); }; return [this]() { return PollPullClientInitialMetadata(); };
} }
// Pull a message. Returns a promise that resolves to a // Pull a message. Returns a promise that resolves to a
// ValueOrFailure<absl::optional<MessageHandle>>. // ValueOrFailure<std::optional<MessageHandle>>.
GRPC_MUST_USE_RESULT auto PullMessage() { GRPC_MUST_USE_RESULT auto PullMessage() {
return [this]() { return PollPullMessage(); }; return [this]() { return PollPullMessage(); };
} }
@ -62,7 +62,7 @@ class RequestBuffer {
friend class RequestBuffer; friend class RequestBuffer;
Poll<ValueOrFailure<ClientMetadataHandle>> PollPullClientInitialMetadata(); Poll<ValueOrFailure<ClientMetadataHandle>> PollPullClientInitialMetadata();
Poll<ValueOrFailure<absl::optional<MessageHandle>>> PollPullMessage(); Poll<ValueOrFailure<std::optional<MessageHandle>>> PollPullMessage();
template <typename T> template <typename T>
T ClaimObject(T& object) ABSL_EXCLUSIVE_LOCKS_REQUIRED(buffer_->mu_) { T ClaimObject(T& object) ABSL_EXCLUSIVE_LOCKS_REQUIRED(buffer_->mu_) {
@ -143,7 +143,7 @@ class RequestBuffer {
explicit Cancelled(absl::Status error) : error(std::move(error)) {} explicit Cancelled(absl::Status error) : error(std::move(error)) {}
absl::Status error; absl::Status error;
}; };
using State = absl::variant<Buffering, Buffered, Streaming, Cancelled>; using State = std::variant<Buffering, Buffered, Streaming, Cancelled>;
Poll<ValueOrFailure<size_t>> PollPushMessage(MessageHandle& message); Poll<ValueOrFailure<size_t>> PollPushMessage(MessageHandle& message);
Pending PendingPull(Reader* reader) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { Pending PendingPull(Reader* reader) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
@ -155,7 +155,7 @@ class RequestBuffer {
return Pending{}; return Pending{};
} }
void MaybeSwitchToStreaming() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { void MaybeSwitchToStreaming() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
auto& buffering = absl::get<Buffering>(state_); auto& buffering = std::get<Buffering>(state_);
if (winner_ == nullptr) return; if (winner_ == nullptr) return;
if (winner_->message_index_ < buffering.messages.size()) return; if (winner_->message_index_ < buffering.messages.size()) return;
state_.emplace<Streaming>(); state_.emplace<Streaming>();

View File

@ -334,7 +334,7 @@ ServerNode::~ServerNode() {}
void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) { void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) {
MutexLock lock(&child_mu_); MutexLock lock(&child_mu_);
child_sockets_.insert(std::make_pair(node->uuid(), std::move(node))); child_sockets_.insert(std::pair(node->uuid(), std::move(node)));
} }
void ServerNode::RemoveChildSocket(intptr_t child_uuid) { void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
@ -344,7 +344,7 @@ void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
void ServerNode::AddChildListenSocket(RefCountedPtr<ListenSocketNode> node) { void ServerNode::AddChildListenSocket(RefCountedPtr<ListenSocketNode> node) {
MutexLock lock(&child_mu_); MutexLock lock(&child_mu_);
child_listen_sockets_.insert(std::make_pair(node->uuid(), std::move(node))); child_listen_sockets_.insert(std::pair(node->uuid(), std::move(node)));
} }
void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) { void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) {

View File

@ -28,13 +28,13 @@
#include <atomic> #include <atomic>
#include <cstdint> #include <cstdint>
#include <map> #include <map>
#include <optional>
#include <set> #include <set>
#include <string> #include <string>
#include <utility> #include <utility>
#include "absl/base/thread_annotations.h" #include "absl/base/thread_annotations.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/channelz/channel_trace.h" #include "src/core/channelz/channel_trace.h"
#include "src/core/util/json/json.h" #include "src/core/util/json/json.h"
#include "src/core/util/per_cpu.h" #include "src/core/util/per_cpu.h"
@ -152,31 +152,12 @@ class PerCpuCallCountingHelper final {
// We want to ensure that this per-cpu data structure lands on different // We want to ensure that this per-cpu data structure lands on different
// cachelines per cpu. // cachelines per cpu.
// With C++17 we can do so explicitly with an `alignas` specifier.
// Prior versions we can at best approximate it by padding the structure.
// It'll probably work out ok, but it's not guaranteed across allocators.
// (in the bad case where this gets split across cachelines we'll just have
// two cpus fighting over the same cacheline with a slight performance
// degregation).
// TODO(ctiller): When we move to C++17 delete the duplicate definition.
#if __cplusplus >= 201703L
struct alignas(GPR_CACHELINE_SIZE) PerCpuData { struct alignas(GPR_CACHELINE_SIZE) PerCpuData {
std::atomic<int64_t> calls_started{0}; std::atomic<int64_t> calls_started{0};
std::atomic<int64_t> calls_succeeded{0}; std::atomic<int64_t> calls_succeeded{0};
std::atomic<int64_t> calls_failed{0}; std::atomic<int64_t> calls_failed{0};
std::atomic<gpr_cycle_counter> last_call_started_cycle{0}; std::atomic<gpr_cycle_counter> last_call_started_cycle{0};
}; };
#else
struct PerCpuDataHeader {
std::atomic<int64_t> calls_started{0};
std::atomic<int64_t> calls_succeeded{0};
std::atomic<int64_t> calls_failed{0};
std::atomic<gpr_cycle_counter> last_call_started_cycle{0};
};
struct PerCpuData : public PerCpuDataHeader {
uint8_t padding[GPR_CACHELINE_SIZE - sizeof(PerCpuDataHeader)];
};
#endif
PerCpu<PerCpuData> per_cpu_data_{PerCpuOptions().SetCpusPerShard(4)}; PerCpu<PerCpuData> per_cpu_data_{PerCpuOptions().SetCpusPerShard(4)};
}; };
@ -346,8 +327,8 @@ class SocketNode final : public BaseNode {
}; };
enum class ModelType { kUnset = 0, kTls = 1, kOther = 2 }; enum class ModelType { kUnset = 0, kTls = 1, kOther = 2 };
ModelType type = ModelType::kUnset; ModelType type = ModelType::kUnset;
absl::optional<Tls> tls; std::optional<Tls> tls;
absl::optional<Json> other; std::optional<Json> other;
Json RenderJson(); Json RenderJson();

View File

@ -178,7 +178,6 @@ void ChannelzRegistry::InternalLogAllEntities() {
} // namespace grpc_core } // namespace grpc_core
char* grpc_channelz_get_top_channels(intptr_t start_channel_id) { char* grpc_channelz_get_top_channels(intptr_t start_channel_id) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
return gpr_strdup( return gpr_strdup(
grpc_core::channelz::ChannelzRegistry::GetTopChannels(start_channel_id) grpc_core::channelz::ChannelzRegistry::GetTopChannels(start_channel_id)
@ -186,7 +185,6 @@ char* grpc_channelz_get_top_channels(intptr_t start_channel_id) {
} }
char* grpc_channelz_get_servers(intptr_t start_server_id) { char* grpc_channelz_get_servers(intptr_t start_server_id) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
return gpr_strdup( return gpr_strdup(
grpc_core::channelz::ChannelzRegistry::GetServers(start_server_id) grpc_core::channelz::ChannelzRegistry::GetServers(start_server_id)
@ -194,7 +192,6 @@ char* grpc_channelz_get_servers(intptr_t start_server_id) {
} }
char* grpc_channelz_get_server(intptr_t server_id) { char* grpc_channelz_get_server(intptr_t server_id) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> server_node = grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> server_node =
grpc_core::channelz::ChannelzRegistry::Get(server_id); grpc_core::channelz::ChannelzRegistry::Get(server_id);
@ -212,7 +209,6 @@ char* grpc_channelz_get_server(intptr_t server_id) {
char* grpc_channelz_get_server_sockets(intptr_t server_id, char* grpc_channelz_get_server_sockets(intptr_t server_id,
intptr_t start_socket_id, intptr_t start_socket_id,
intptr_t max_results) { intptr_t max_results) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
// Validate inputs before handing them of to the renderer. // Validate inputs before handing them of to the renderer.
grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> base_node = grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> base_node =
@ -231,7 +227,6 @@ char* grpc_channelz_get_server_sockets(intptr_t server_id,
} }
char* grpc_channelz_get_channel(intptr_t channel_id) { char* grpc_channelz_get_channel(intptr_t channel_id) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> channel_node = grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> channel_node =
grpc_core::channelz::ChannelzRegistry::Get(channel_id); grpc_core::channelz::ChannelzRegistry::Get(channel_id);
@ -249,7 +244,6 @@ char* grpc_channelz_get_channel(intptr_t channel_id) {
} }
char* grpc_channelz_get_subchannel(intptr_t subchannel_id) { char* grpc_channelz_get_subchannel(intptr_t subchannel_id) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> subchannel_node = grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> subchannel_node =
grpc_core::channelz::ChannelzRegistry::Get(subchannel_id); grpc_core::channelz::ChannelzRegistry::Get(subchannel_id);
@ -265,7 +259,6 @@ char* grpc_channelz_get_subchannel(intptr_t subchannel_id) {
} }
char* grpc_channelz_get_socket(intptr_t socket_id) { char* grpc_channelz_get_socket(intptr_t socket_id) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> socket_node = grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> socket_node =
grpc_core::channelz::ChannelzRegistry::Get(socket_id); grpc_core::channelz::ChannelzRegistry::Get(socket_id);

View File

@ -29,9 +29,11 @@
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <new> #include <new>
#include <optional>
#include <set> #include <set>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#include <variant>
#include <vector> #include <vector>
#include "absl/cleanup/cleanup.h" #include "absl/cleanup/cleanup.h"
@ -43,8 +45,6 @@
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h" #include "absl/strings/str_join.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "src/core/client_channel/client_channel_internal.h" #include "src/core/client_channel/client_channel_internal.h"
#include "src/core/client_channel/client_channel_service_config.h" #include "src/core/client_channel/client_channel_service_config.h"
#include "src/core/client_channel/config_selector.h" #include "src/core/client_channel/config_selector.h"
@ -243,8 +243,7 @@ class ClientChannel::SubchannelWrapper::WatcherWrapper
*subchannel_wrapper_->client_channel_->work_serializer_) { *subchannel_wrapper_->client_channel_->work_serializer_) {
ApplyUpdateInControlPlaneWorkSerializer(state, status); ApplyUpdateInControlPlaneWorkSerializer(state, status);
Unref(); Unref();
}, });
DEBUG_LOCATION);
} }
grpc_pollset_set* interested_parties() override { return nullptr; } grpc_pollset_set* interested_parties() override { return nullptr; }
@ -262,8 +261,7 @@ class ClientChannel::SubchannelWrapper::WatcherWrapper
<< subchannel_wrapper_->subchannel_.get() << subchannel_wrapper_->subchannel_.get()
<< " watcher=" << watcher_.get() << " watcher=" << watcher_.get()
<< " state=" << ConnectivityStateName(state) << " status=" << status; << " state=" << ConnectivityStateName(state) << " status=" << status;
absl::optional<absl::Cord> keepalive_throttling = auto keepalive_throttling = status.GetPayload(kKeepaliveThrottlingKey);
status.GetPayload(kKeepaliveThrottlingKey);
if (keepalive_throttling.has_value()) { if (keepalive_throttling.has_value()) {
int new_keepalive_time = -1; int new_keepalive_time = -1;
if (absl::SimpleAtoi(std::string(keepalive_throttling.value()), if (absl::SimpleAtoi(std::string(keepalive_throttling.value()),
@ -368,8 +366,7 @@ void ClientChannel::SubchannelWrapper::Orphaned() {
} }
} }
} }
}, });
DEBUG_LOCATION);
} }
void ClientChannel::SubchannelWrapper::WatchConnectivityState( void ClientChannel::SubchannelWrapper::WatchConnectivityState(
@ -557,7 +554,7 @@ absl::StatusOr<RefCountedPtr<Channel>> ClientChannel::Create(
} }
// Get default service config. If none is specified via the client API, // Get default service config. If none is specified via the client API,
// we use an empty config. // we use an empty config.
absl::optional<absl::string_view> service_config_json = std::optional<absl::string_view> service_config_json =
channel_args.GetString(GRPC_ARG_SERVICE_CONFIG); channel_args.GetString(GRPC_ARG_SERVICE_CONFIG);
if (!service_config_json.has_value()) service_config_json = "{}"; if (!service_config_json.has_value()) service_config_json = "{}";
auto default_service_config = auto default_service_config =
@ -592,7 +589,7 @@ absl::StatusOr<RefCountedPtr<Channel>> ClientChannel::Create(
namespace { namespace {
std::string GetDefaultAuthorityFromChannelArgs(const ChannelArgs& channel_args, std::string GetDefaultAuthorityFromChannelArgs(const ChannelArgs& channel_args,
absl::string_view target) { absl::string_view target) {
absl::optional<std::string> default_authority = std::optional<std::string> default_authority =
channel_args.GetOwnedString(GRPC_ARG_DEFAULT_AUTHORITY); channel_args.GetOwnedString(GRPC_ARG_DEFAULT_AUTHORITY);
if (!default_authority.has_value()) { if (!default_authority.has_value()) {
return CoreConfiguration::Get().resolver_registry().GetDefaultAuthority( return CoreConfiguration::Get().resolver_registry().GetDefaultAuthority(
@ -661,8 +658,7 @@ void ClientChannel::Orphaned() {
work_serializer_->Run( work_serializer_->Run(
[self]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) { [self]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) {
self->DestroyResolverAndLbPolicyLocked(); self->DestroyResolverAndLbPolicyLocked();
}, });
DEBUG_LOCATION);
// IncreaseCallCount() introduces a phony call and prevents the idle // IncreaseCallCount() introduces a phony call and prevents the idle
// timer from being reset by other threads. // timer from being reset by other threads.
idle_state_.IncreaseCallCount(); idle_state_.IncreaseCallCount();
@ -682,8 +678,7 @@ grpc_connectivity_state ClientChannel::CheckConnectivityState(
work_serializer_->Run( work_serializer_->Run(
[self]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) { [self]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) {
self->TryToConnectLocked(); self->TryToConnectLocked();
}, });
DEBUG_LOCATION);
} }
return state; return state;
} }
@ -708,7 +703,6 @@ class ExternalStateWatcher : public RefCounted<ExternalStateWatcher> {
const Duration timeout = deadline - Timestamp::Now(); const Duration timeout = deadline - Timestamp::Now();
timer_handle_ = timer_handle_ =
channel_->event_engine()->RunAfter(timeout, [self = Ref()]() mutable { channel_->event_engine()->RunAfter(timeout, [self = Ref()]() mutable {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
self->MaybeStartCompletion(absl::DeadlineExceededError( self->MaybeStartCompletion(absl::DeadlineExceededError(
"Timed out waiting for connection state change")); "Timed out waiting for connection state change"));
@ -788,8 +782,7 @@ void ClientChannel::AddConnectivityWatcher(
// watcher = std::move(watcher)]() // watcher = std::move(watcher)]()
// ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_) { // ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_) {
// self->state_tracker_.AddWatcher(initial_state, std::move(watcher)); // self->state_tracker_.AddWatcher(initial_state, std::move(watcher));
// }, // });
// DEBUG_LOCATION);
} }
void ClientChannel::RemoveConnectivityWatcher( void ClientChannel::RemoveConnectivityWatcher(
@ -798,8 +791,7 @@ void ClientChannel::RemoveConnectivityWatcher(
work_serializer_->Run( work_serializer_->Run(
[self, watcher]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) { [self, watcher]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) {
self->state_tracker_.RemoveWatcher(watcher); self->state_tracker_.RemoveWatcher(watcher);
}, });
DEBUG_LOCATION);
} }
void ClientChannel::GetInfo(const grpc_channel_info* info) { void ClientChannel::GetInfo(const grpc_channel_info* info) {
@ -817,8 +809,7 @@ void ClientChannel::ResetConnectionBackoff() {
work_serializer_->Run( work_serializer_->Run(
[self]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) { [self]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*self->work_serializer_) {
if (self->lb_policy_ != nullptr) self->lb_policy_->ResetBackoffLocked(); if (self->lb_policy_ != nullptr) self->lb_policy_->ResetBackoffLocked();
}, });
DEBUG_LOCATION);
} }
namespace { namespace {
@ -855,7 +846,7 @@ void ClientChannel::Ping(grpc_completion_queue*, void*) {
grpc_call* ClientChannel::CreateCall( grpc_call* ClientChannel::CreateCall(
grpc_call* parent_call, uint32_t propagation_mask, grpc_call* parent_call, uint32_t propagation_mask,
grpc_completion_queue* cq, grpc_pollset_set* /*pollset_set_alternative*/, grpc_completion_queue* cq, grpc_pollset_set* /*pollset_set_alternative*/,
Slice path, absl::optional<Slice> authority, Timestamp deadline, bool) { Slice path, std::optional<Slice> authority, Timestamp deadline, bool) {
auto arena = call_arena_allocator()->MakeArena(); auto arena = call_arena_allocator()->MakeArena();
arena->SetContext<grpc_event_engine::experimental::EventEngine>( arena->SetContext<grpc_event_engine::experimental::EventEngine>(
event_engine()); event_engine());
@ -985,7 +976,7 @@ RefCountedPtr<LoadBalancingPolicy::Config> ChooseLbPolicy(
} }
// Try the deprecated LB policy name from the service config. // Try the deprecated LB policy name from the service config.
// If not, try the setting from channel args. // If not, try the setting from channel args.
absl::optional<absl::string_view> policy_name; std::optional<absl::string_view> policy_name;
if (!parsed_service_config->parsed_deprecated_lb_policy().empty()) { if (!parsed_service_config->parsed_deprecated_lb_policy().empty()) {
policy_name = parsed_service_config->parsed_deprecated_lb_policy(); policy_name = parsed_service_config->parsed_deprecated_lb_policy();
} else { } else {
@ -1189,7 +1180,7 @@ void ClientChannel::OnResolverErrorLocked(absl::Status status) {
absl::Status ClientChannel::CreateOrUpdateLbPolicyLocked( absl::Status ClientChannel::CreateOrUpdateLbPolicyLocked(
RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config, RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
const absl::optional<std::string>& health_check_service_name, const std::optional<std::string>& health_check_service_name,
Resolver::Result result) { Resolver::Result result) {
// Construct update. // Construct update.
LoadBalancingPolicy::UpdateArgs update_args; LoadBalancingPolicy::UpdateArgs update_args;
@ -1368,8 +1359,7 @@ void ClientChannel::StartIdleTimer() {
// might need to check for any calls that are // might need to check for any calls that are
// queued waiting for a resolver result or an LB // queued waiting for a resolver result or an LB
// pick. // pick.
}, });
DEBUG_LOCATION);
} }
}, },
std::move(arena))); std::move(arena)));

View File

@ -74,7 +74,7 @@ class ClientChannel : public Channel {
grpc_call* CreateCall(grpc_call* parent_call, uint32_t propagation_mask, grpc_call* CreateCall(grpc_call* parent_call, uint32_t propagation_mask,
grpc_completion_queue* cq, grpc_completion_queue* cq,
grpc_pollset_set* /*pollset_set_alternative*/, grpc_pollset_set* /*pollset_set_alternative*/,
Slice path, absl::optional<Slice> authority, Slice path, std::optional<Slice> authority,
Timestamp deadline, bool registered_method) override; Timestamp deadline, bool registered_method) override;
void StartCall(UnstartedCallHandler unstarted_handler) override; void StartCall(UnstartedCallHandler unstarted_handler) override;
@ -139,7 +139,7 @@ class ClientChannel : public Channel {
absl::Status CreateOrUpdateLbPolicyLocked( absl::Status CreateOrUpdateLbPolicyLocked(
RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config, RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
const absl::optional<std::string>& health_check_service_name, const std::optional<std::string>& health_check_service_name,
Resolver::Result result) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_); Resolver::Result result) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_);
OrphanablePtr<LoadBalancingPolicy> CreateLbPolicyLocked( OrphanablePtr<LoadBalancingPolicy> CreateLbPolicyLocked(
const ChannelArgs& args) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_); const ChannelArgs& args) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_);

View File

@ -30,9 +30,11 @@
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <new> #include <new>
#include <optional>
#include <set> #include <set>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#include <variant>
#include <vector> #include <vector>
#include "absl/cleanup/cleanup.h" #include "absl/cleanup/cleanup.h"
@ -45,8 +47,6 @@
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h" #include "absl/strings/str_join.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "src/core/channelz/channel_trace.h" #include "src/core/channelz/channel_trace.h"
#include "src/core/client_channel/backup_poller.h" #include "src/core/client_channel/backup_poller.h"
#include "src/core/client_channel/client_channel_internal.h" #include "src/core/client_channel/client_channel_internal.h"
@ -139,14 +139,14 @@ class ClientChannelFilter::CallData {
// Checks whether a resolver result is available. The following // Checks whether a resolver result is available. The following
// outcomes are possible: // outcomes are possible:
// - No resolver result is available yet. The call will be queued and // - No resolver result is available yet. The call will be queued and
// absl::nullopt will be returned. Later, when a resolver result // std::nullopt will be returned. Later, when a resolver result
// becomes available, RetryCheckResolutionLocked() will be called. // becomes available, RetryCheckResolutionLocked() will be called.
// - The resolver has returned a transient failure. If the call is // - The resolver has returned a transient failure. If the call is
// not wait_for_ready, a non-OK status will be returned. (If the // not wait_for_ready, a non-OK status will be returned. (If the
// call *is* wait_for_ready, it will be queued instead.) // call *is* wait_for_ready, it will be queued instead.)
// - There is a valid resolver result. The service config will be // - There is a valid resolver result. The service config will be
// stored in the call context and an OK status will be returned. // stored in the call context and an OK status will be returned.
absl::optional<absl::Status> CheckResolution(bool was_queued); std::optional<absl::Status> CheckResolution(bool was_queued);
private: private:
// Accessors for data stored in the subclass. // Accessors for data stored in the subclass.
@ -521,7 +521,16 @@ class ClientChannelFilter::SubchannelWrapper final
GRPC_TRACE_LOG(client_channel, INFO) GRPC_TRACE_LOG(client_channel, INFO)
<< "chand=" << chand_ << ": destroying subchannel wrapper " << this << "chand=" << chand_ << ": destroying subchannel wrapper " << this
<< "for subchannel " << subchannel_.get(); << "for subchannel " << subchannel_.get();
if (!IsWorkSerializerDispatchEnabled()) { GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_, "SubchannelWrapper");
}
void Orphaned() override {
// Make sure we clean up the channel's subchannel maps inside the
// WorkSerializer.
// Ref held by callback.
WeakRef(DEBUG_LOCATION, "subchannel map cleanup").release();
chand_->work_serializer_->Run([this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(
*chand_->work_serializer_) {
chand_->subchannel_wrappers_.erase(this); chand_->subchannel_wrappers_.erase(this);
if (chand_->channelz_node_ != nullptr) { if (chand_->channelz_node_ != nullptr) {
auto* subchannel_node = subchannel_->channelz_node(); auto* subchannel_node = subchannel_->channelz_node();
@ -536,36 +545,8 @@ class ClientChannelFilter::SubchannelWrapper final
} }
} }
} }
}
GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_, "SubchannelWrapper");
}
void Orphaned() override {
if (!IsWorkSerializerDispatchEnabled()) return;
// Make sure we clean up the channel's subchannel maps inside the
// WorkSerializer.
// Ref held by callback.
WeakRef(DEBUG_LOCATION, "subchannel map cleanup").release();
chand_->work_serializer_->Run(
[this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) {
chand_->subchannel_wrappers_.erase(this);
if (chand_->channelz_node_ != nullptr) {
auto* subchannel_node = subchannel_->channelz_node();
if (subchannel_node != nullptr) {
auto it =
chand_->subchannel_refcount_map_.find(subchannel_.get());
CHECK(it != chand_->subchannel_refcount_map_.end());
--it->second;
if (it->second == 0) {
chand_->channelz_node_->RemoveChildSubchannel(
subchannel_node->uuid());
chand_->subchannel_refcount_map_.erase(it);
}
}
}
WeakUnref(DEBUG_LOCATION, "subchannel map cleanup"); WeakUnref(DEBUG_LOCATION, "subchannel map cleanup");
}, });
DEBUG_LOCATION);
} }
void WatchConnectivityState( void WatchConnectivityState(
@ -639,16 +620,6 @@ class ClientChannelFilter::SubchannelWrapper final
: watcher_(std::move(watcher)), parent_(std::move(parent)) {} : watcher_(std::move(watcher)), parent_(std::move(parent)) {}
~WatcherWrapper() override { ~WatcherWrapper() override {
if (!IsWorkSerializerDispatchEnabled()) {
auto* parent = parent_.release(); // ref owned by lambda
parent->chand_->work_serializer_->Run(
[parent]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(
*parent_->chand_->work_serializer_) {
parent->Unref(DEBUG_LOCATION, "WatcherWrapper");
},
DEBUG_LOCATION);
return;
}
parent_.reset(DEBUG_LOCATION, "WatcherWrapper"); parent_.reset(DEBUG_LOCATION, "WatcherWrapper");
} }
@ -666,8 +637,7 @@ class ClientChannelFilter::SubchannelWrapper final
*parent_->chand_->work_serializer_) { *parent_->chand_->work_serializer_) {
ApplyUpdateInControlPlaneWorkSerializer(state, status); ApplyUpdateInControlPlaneWorkSerializer(state, status);
Unref(); Unref();
}, });
DEBUG_LOCATION);
} }
grpc_pollset_set* interested_parties() override { grpc_pollset_set* interested_parties() override {
@ -685,8 +655,7 @@ class ClientChannelFilter::SubchannelWrapper final
<< parent_.get() << " subchannel " << parent_->subchannel_.get() << parent_.get() << " subchannel " << parent_->subchannel_.get()
<< " watcher=" << watcher_.get() << " watcher=" << watcher_.get()
<< " state=" << ConnectivityStateName(state) << " status=" << status; << " state=" << ConnectivityStateName(state) << " status=" << status;
absl::optional<absl::Cord> keepalive_throttling = auto keepalive_throttling = status.GetPayload(kKeepaliveThrottlingKey);
status.GetPayload(kKeepaliveThrottlingKey);
if (keepalive_throttling.has_value()) { if (keepalive_throttling.has_value()) {
int new_keepalive_time = -1; int new_keepalive_time = -1;
if (absl::SimpleAtoi(std::string(keepalive_throttling.value()), if (absl::SimpleAtoi(std::string(keepalive_throttling.value()),
@ -787,8 +756,7 @@ ClientChannelFilter::ExternalConnectivityWatcher::ExternalConnectivityWatcher(
[this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) { [this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) {
// The ref is passed to AddWatcherLocked(). // The ref is passed to AddWatcherLocked().
AddWatcherLocked(); AddWatcherLocked();
}, });
DEBUG_LOCATION);
} }
ClientChannelFilter::ExternalConnectivityWatcher:: ClientChannelFilter::ExternalConnectivityWatcher::
@ -841,8 +809,7 @@ void ClientChannelFilter::ExternalConnectivityWatcher::Notify(
[this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) { [this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) {
RemoveWatcherLocked(); RemoveWatcherLocked();
Unref(DEBUG_LOCATION, "RemoveWatcherLocked()"); Unref(DEBUG_LOCATION, "RemoveWatcherLocked()");
}, });
DEBUG_LOCATION);
} }
} }
@ -861,8 +828,7 @@ void ClientChannelFilter::ExternalConnectivityWatcher::Cancel() {
[this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) { [this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) {
RemoveWatcherLocked(); RemoveWatcherLocked();
Unref(DEBUG_LOCATION, "RemoveWatcherLocked()"); Unref(DEBUG_LOCATION, "RemoveWatcherLocked()");
}, });
DEBUG_LOCATION);
} }
void ClientChannelFilter::ExternalConnectivityWatcher::AddWatcherLocked() { void ClientChannelFilter::ExternalConnectivityWatcher::AddWatcherLocked() {
@ -892,8 +858,7 @@ class ClientChannelFilter::ConnectivityWatcherAdder final {
chand_->work_serializer_->Run( chand_->work_serializer_->Run(
[this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) { [this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) {
AddWatcherLocked(); AddWatcherLocked();
}, });
DEBUG_LOCATION);
} }
private: private:
@ -922,8 +887,7 @@ class ClientChannelFilter::ConnectivityWatcherRemover final {
chand_->work_serializer_->Run( chand_->work_serializer_->Run(
[this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) { [this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand_->work_serializer_) {
RemoveWatcherLocked(); RemoveWatcherLocked();
}, });
DEBUG_LOCATION);
} }
private: private:
@ -1102,7 +1066,7 @@ ClientChannelFilter::ClientChannelFilter(grpc_channel_element_args* args,
} }
// Get default service config. If none is specified via the client API, // Get default service config. If none is specified via the client API,
// we use an empty config. // we use an empty config.
absl::optional<absl::string_view> service_config_json = std::optional<absl::string_view> service_config_json =
channel_args_.GetString(GRPC_ARG_SERVICE_CONFIG); channel_args_.GetString(GRPC_ARG_SERVICE_CONFIG);
if (!service_config_json.has_value()) service_config_json = "{}"; if (!service_config_json.has_value()) service_config_json = "{}";
*error = absl::OkStatus(); *error = absl::OkStatus();
@ -1114,7 +1078,7 @@ ClientChannelFilter::ClientChannelFilter(grpc_channel_element_args* args,
} }
default_service_config_ = std::move(*service_config); default_service_config_ = std::move(*service_config);
// Get URI to resolve, using proxy mapper if needed. // Get URI to resolve, using proxy mapper if needed.
absl::optional<std::string> target_uri = std::optional<std::string> target_uri =
channel_args_.GetOwnedString(GRPC_ARG_SERVER_URI); channel_args_.GetOwnedString(GRPC_ARG_SERVER_URI);
if (!target_uri.has_value()) { if (!target_uri.has_value()) {
*error = GRPC_ERROR_CREATE( *error = GRPC_ERROR_CREATE(
@ -1146,7 +1110,7 @@ ClientChannelFilter::ClientChannelFilter(grpc_channel_element_args* args,
keepalive_time_ = -1; // unset keepalive_time_ = -1; // unset
} }
// Set default authority. // Set default authority.
absl::optional<std::string> default_authority = std::optional<std::string> default_authority =
channel_args_.GetOwnedString(GRPC_ARG_DEFAULT_AUTHORITY); channel_args_.GetOwnedString(GRPC_ARG_DEFAULT_AUTHORITY);
if (!default_authority.has_value()) { if (!default_authority.has_value()) {
default_authority_ = default_authority_ =
@ -1199,7 +1163,7 @@ RefCountedPtr<LoadBalancingPolicy::Config> ChooseLbPolicy(
} }
// Try the deprecated LB policy name from the service config. // Try the deprecated LB policy name from the service config.
// If not, try the setting from channel args. // If not, try the setting from channel args.
absl::optional<absl::string_view> policy_name; std::optional<absl::string_view> policy_name;
if (!parsed_service_config->parsed_deprecated_lb_policy().empty()) { if (!parsed_service_config->parsed_deprecated_lb_policy().empty()) {
policy_name = parsed_service_config->parsed_deprecated_lb_policy(); policy_name = parsed_service_config->parsed_deprecated_lb_policy();
} else { } else {
@ -1406,7 +1370,7 @@ void ClientChannelFilter::OnResolverErrorLocked(absl::Status status) {
absl::Status ClientChannelFilter::CreateOrUpdateLbPolicyLocked( absl::Status ClientChannelFilter::CreateOrUpdateLbPolicyLocked(
RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config, RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
const absl::optional<std::string>& health_check_service_name, const std::optional<std::string>& health_check_service_name,
Resolver::Result result) { Resolver::Result result) {
// Construct update. // Construct update.
LoadBalancingPolicy::UpdateArgs update_args; LoadBalancingPolicy::UpdateArgs update_args;
@ -1631,22 +1595,22 @@ T HandlePickResult(
std::function<T(LoadBalancingPolicy::PickResult::Fail*)> fail_func, std::function<T(LoadBalancingPolicy::PickResult::Fail*)> fail_func,
std::function<T(LoadBalancingPolicy::PickResult::Drop*)> drop_func) { std::function<T(LoadBalancingPolicy::PickResult::Drop*)> drop_func) {
auto* complete_pick = auto* complete_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Complete>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Complete>(&result->result);
if (complete_pick != nullptr) { if (complete_pick != nullptr) {
return complete_func(complete_pick); return complete_func(complete_pick);
} }
auto* queue_pick = auto* queue_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Queue>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Queue>(&result->result);
if (queue_pick != nullptr) { if (queue_pick != nullptr) {
return queue_func(queue_pick); return queue_func(queue_pick);
} }
auto* fail_pick = auto* fail_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Fail>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Fail>(&result->result);
if (fail_pick != nullptr) { if (fail_pick != nullptr) {
return fail_func(fail_pick); return fail_func(fail_pick);
} }
auto* drop_pick = auto* drop_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Drop>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Drop>(&result->result);
CHECK_NE(drop_pick, nullptr); CHECK_NE(drop_pick, nullptr);
return drop_func(drop_pick); return drop_func(drop_pick);
} }
@ -1768,8 +1732,7 @@ void ClientChannelFilter::StartTransportOp(grpc_channel_element* elem,
chand->work_serializer_->Run( chand->work_serializer_->Run(
[chand, op]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand->work_serializer_) { [chand, op]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand->work_serializer_) {
chand->StartTransportOpLocked(op); chand->StartTransportOpLocked(op);
}, });
DEBUG_LOCATION);
} }
void ClientChannelFilter::GetChannelInfo(grpc_channel_element* elem, void ClientChannelFilter::GetChannelInfo(grpc_channel_element* elem,
@ -1806,8 +1769,7 @@ grpc_connectivity_state ClientChannelFilter::CheckConnectivityState(
if (out == GRPC_CHANNEL_IDLE && try_to_connect) { if (out == GRPC_CHANNEL_IDLE && try_to_connect) {
GRPC_CHANNEL_STACK_REF(owning_stack_, "TryToConnect"); GRPC_CHANNEL_STACK_REF(owning_stack_, "TryToConnect");
work_serializer_->Run([this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED( work_serializer_->Run([this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(
*work_serializer_) { TryToConnectLocked(); }, *work_serializer_) { TryToConnectLocked(); });
DEBUG_LOCATION);
} }
return out; return out;
} }
@ -1898,7 +1860,7 @@ grpc_error_handle ClientChannelFilter::CallData::ApplyServiceConfigToCallLocked(
return absl::OkStatus(); return absl::OkStatus();
} }
absl::optional<absl::Status> ClientChannelFilter::CallData::CheckResolution( std::optional<absl::Status> ClientChannelFilter::CallData::CheckResolution(
bool was_queued) { bool was_queued) {
// Check if we have a resolver result to use. // Check if we have a resolver result to use.
absl::StatusOr<RefCountedPtr<ConfigSelector>> config_selector; absl::StatusOr<RefCountedPtr<ConfigSelector>> config_selector;
@ -1908,19 +1870,11 @@ absl::optional<absl::Status> ClientChannelFilter::CallData::CheckResolution(
// If no result is available, queue the call. // If no result is available, queue the call.
if (!result_ready) { if (!result_ready) {
AddCallToResolverQueuedCallsLocked(); AddCallToResolverQueuedCallsLocked();
return absl::nullopt; return std::nullopt;
} }
} }
// We have a result. Apply service config to call. // We have a result. Apply service config to call.
grpc_error_handle error = ApplyServiceConfigToCallLocked(config_selector); grpc_error_handle error = ApplyServiceConfigToCallLocked(config_selector);
// ConfigSelector must be unreffed inside the WorkSerializer.
if (!IsWorkSerializerDispatchEnabled() && config_selector.ok()) {
chand()->work_serializer_->Run(
[config_selector = std::move(*config_selector)]() mutable {
config_selector.reset();
},
DEBUG_LOCATION);
}
// Handle errors. // Handle errors.
if (!error.ok()) { if (!error.ok()) {
GRPC_TRACE_LOG(client_channel_call, INFO) GRPC_TRACE_LOG(client_channel_call, INFO)
@ -2097,8 +2051,7 @@ void ClientChannelFilter::FilterBasedCallData::StartTransportStreamOpBatch(
[chand]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand->work_serializer_) { [chand]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*chand->work_serializer_) {
chand->CheckConnectivityState(/*try_to_connect=*/true); chand->CheckConnectivityState(/*try_to_connect=*/true);
GRPC_CHANNEL_STACK_UNREF(chand->owning_stack_, "ExitIdle"); GRPC_CHANNEL_STACK_UNREF(chand->owning_stack_, "ExitIdle");
}, });
DEBUG_LOCATION);
} }
calld->TryCheckResolution(/*was_queued=*/false); calld->TryCheckResolution(/*was_queued=*/false);
} else { } else {
@ -2293,7 +2246,6 @@ void ClientChannelFilter::FilterBasedCallData::RetryCheckResolutionLocked() {
// Do an async callback to resume call processing, so that we're not // Do an async callback to resume call processing, so that we're not
// doing it while holding the channel's resolution mutex. // doing it while holding the channel's resolution mutex.
chand()->owning_stack_->EventEngine()->Run([this]() { chand()->owning_stack_->EventEngine()->Run([this]() {
ApplicationCallbackExecCtx application_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
TryCheckResolution(/*was_queued=*/true); TryCheckResolution(/*was_queued=*/true);
}); });
@ -2427,12 +2379,14 @@ class ClientChannelFilter::LoadBalancedCall::BackendMetricAccessor final
namespace { namespace {
void CreateCallAttemptTracer(Arena* arena, bool is_transparent_retry) { ClientCallTracer::CallAttemptTracer* CreateCallAttemptTracer(
Arena* arena, bool is_transparent_retry) {
auto* call_tracer = DownCast<ClientCallTracer*>( auto* call_tracer = DownCast<ClientCallTracer*>(
arena->GetContext<CallTracerAnnotationInterface>()); arena->GetContext<CallTracerAnnotationInterface>());
if (call_tracer == nullptr) return; if (call_tracer == nullptr) return nullptr;
auto* tracer = call_tracer->StartNewAttempt(is_transparent_retry); auto* tracer = call_tracer->StartNewAttempt(is_transparent_retry);
arena->SetContext<CallTracerInterface>(tracer); arena->SetContext<CallTracerInterface>(tracer);
return tracer;
} }
} // namespace } // namespace
@ -2444,9 +2398,10 @@ ClientChannelFilter::LoadBalancedCall::LoadBalancedCall(
? "LoadBalancedCall" ? "LoadBalancedCall"
: nullptr), : nullptr),
chand_(chand), chand_(chand),
call_attempt_tracer_(
CreateCallAttemptTracer(arena, is_transparent_retry)),
on_commit_(std::move(on_commit)), on_commit_(std::move(on_commit)),
arena_(arena) { arena_(arena) {
CreateCallAttemptTracer(arena, is_transparent_retry);
GRPC_TRACE_LOG(client_channel_lb_call, INFO) GRPC_TRACE_LOG(client_channel_lb_call, INFO)
<< "chand=" << chand_ << " lb_call=" << this << ": created"; << "chand=" << chand_ << " lb_call=" << this << ": created";
} }
@ -2514,51 +2469,21 @@ void ClientChannelFilter::LoadBalancedCall::AddCallToLbQueuedCallsLocked() {
OnAddToQueueLocked(); OnAddToQueueLocked();
} }
absl::optional<absl::Status> std::optional<absl::Status>
ClientChannelFilter::LoadBalancedCall::PickSubchannel(bool was_queued) { ClientChannelFilter::LoadBalancedCall::PickSubchannel(bool was_queued) {
// We may accumulate multiple pickers here, because if a picker says RefCountedPtr<LoadBalancingPolicy::SubchannelPicker> picker;
// to queue the call, we check again to see if the picker has been
// updated before we queue it.
// We need to unref pickers in the WorkSerializer.
std::vector<RefCountedPtr<LoadBalancingPolicy::SubchannelPicker>> pickers;
auto cleanup = absl::MakeCleanup(
[work_serializer = chand_->work_serializer_, &pickers]() {
if (IsWorkSerializerDispatchEnabled()) return;
work_serializer->Run(
[pickers = std::move(pickers)]() mutable {
for (auto& picker : pickers) {
picker.reset(DEBUG_LOCATION, "PickSubchannel");
}
},
DEBUG_LOCATION);
});
absl::AnyInvocable<void(RefCountedPtr<LoadBalancingPolicy::SubchannelPicker>)>
set_picker;
if (!IsWorkSerializerDispatchEnabled()) {
set_picker =
[&](RefCountedPtr<LoadBalancingPolicy::SubchannelPicker> picker) {
pickers.emplace_back(std::move(picker));
};
} else {
pickers.emplace_back();
set_picker =
[&](RefCountedPtr<LoadBalancingPolicy::SubchannelPicker> picker) {
pickers[0] = std::move(picker);
};
}
// Grab mutex and take a ref to the picker. // Grab mutex and take a ref to the picker.
GRPC_TRACE_LOG(client_channel_lb_call, INFO) GRPC_TRACE_LOG(client_channel_lb_call, INFO)
<< "chand=" << chand_ << " lb_call=" << this << "chand=" << chand_ << " lb_call=" << this
<< ": grabbing LB mutex to get picker"; << ": grabbing LB mutex to get picker";
RefCountedPtr<LoadBalancingPolicy::SubchannelPicker> picker;
{ {
MutexLock lock(&chand_->lb_mu_); MutexLock lock(&chand_->lb_mu_);
set_picker(chand_->picker_); picker = chand_->picker_;
} }
while (true) { while (true) {
// TODO(roth): Fix race condition in channel_idle filter and any // TODO(roth): Fix race condition in channel_idle filter and any
// other possible causes of this. // other possible causes of this.
if (pickers.back() == nullptr) { if (picker == nullptr) {
GRPC_TRACE_LOG(client_channel_lb_call, INFO) GRPC_TRACE_LOG(client_channel_lb_call, INFO)
<< "chand=" << chand_ << " lb_call=" << this << "chand=" << chand_ << " lb_call=" << this
<< ": picker is null, failing call"; << ": picker is null, failing call";
@ -2567,27 +2492,25 @@ ClientChannelFilter::LoadBalancedCall::PickSubchannel(bool was_queued) {
// Do pick. // Do pick.
GRPC_TRACE_LOG(client_channel_lb_call, INFO) GRPC_TRACE_LOG(client_channel_lb_call, INFO)
<< "chand=" << chand_ << " lb_call=" << this << "chand=" << chand_ << " lb_call=" << this
<< ": performing pick with picker=" << pickers.back().get(); << ": performing pick with picker=" << picker.get();
grpc_error_handle error; grpc_error_handle error;
bool pick_complete = PickSubchannelImpl(pickers.back().get(), &error); bool pick_complete = PickSubchannelImpl(picker.get(), &error);
if (!pick_complete) { if (!pick_complete) {
RefCountedPtr<LoadBalancingPolicy::SubchannelPicker> old_picker; RefCountedPtr<LoadBalancingPolicy::SubchannelPicker> old_picker;
MutexLock lock(&chand_->lb_mu_); MutexLock lock(&chand_->lb_mu_);
// If picker has been swapped out since we grabbed it, try again. // If picker has been swapped out since we grabbed it, try again.
if (pickers.back() != chand_->picker_) { if (picker != chand_->picker_) {
GRPC_TRACE_LOG(client_channel_lb_call, INFO) GRPC_TRACE_LOG(client_channel_lb_call, INFO)
<< "chand=" << chand_ << " lb_call=" << this << "chand=" << chand_ << " lb_call=" << this
<< ": pick not complete, but picker changed"; << ": pick not complete, but picker changed";
if (IsWorkSerializerDispatchEnabled()) {
// Don't unref until after we release the mutex. // Don't unref until after we release the mutex.
old_picker = std::move(pickers.back()); old_picker = std::move(picker);
} picker = chand_->picker_;
set_picker(chand_->picker_);
continue; continue;
} }
// Otherwise queue the pick to try again later when we get a new picker. // Otherwise queue the pick to try again later when we get a new picker.
AddCallToLbQueuedCallsLocked(); AddCallToLbQueuedCallsLocked();
return absl::nullopt; return std::nullopt;
} }
// Pick is complete. // Pick is complete.
// If it was queued, add a trace annotation. // If it was queued, add a trace annotation.

View File

@ -25,6 +25,7 @@
#include <atomic> #include <atomic>
#include <map> #include <map>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
@ -33,7 +34,6 @@
#include "absl/functional/any_invocable.h" #include "absl/functional/any_invocable.h"
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/channelz/channelz.h" #include "src/core/channelz/channelz.h"
#include "src/core/client_channel/client_channel_args.h" #include "src/core/client_channel/client_channel_args.h"
#include "src/core/client_channel/client_channel_factory.h" #include "src/core/client_channel/client_channel_factory.h"
@ -223,7 +223,7 @@ class ClientChannelFilter final {
absl::Status CreateOrUpdateLbPolicyLocked( absl::Status CreateOrUpdateLbPolicyLocked(
RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config, RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
const absl::optional<std::string>& health_check_service_name, const std::optional<std::string>& health_check_service_name,
Resolver::Result result) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_); Resolver::Result result) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_);
OrphanablePtr<LoadBalancingPolicy> CreateLbPolicyLocked( OrphanablePtr<LoadBalancingPolicy> CreateLbPolicyLocked(
const ChannelArgs& args) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_); const ChannelArgs& args) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*work_serializer_);
@ -374,8 +374,7 @@ class ClientChannelFilter::LoadBalancedCall
protected: protected:
ClientChannelFilter* chand() const { return chand_; } ClientChannelFilter* chand() const { return chand_; }
ClientCallTracer::CallAttemptTracer* call_attempt_tracer() const { ClientCallTracer::CallAttemptTracer* call_attempt_tracer() const {
return DownCast<ClientCallTracer::CallAttemptTracer*>( return call_attempt_tracer_;
arena_->GetContext<CallTracerInterface>());
} }
ConnectedSubchannel* connected_subchannel() const { ConnectedSubchannel* connected_subchannel() const {
return connected_subchannel_.get(); return connected_subchannel_.get();
@ -401,7 +400,7 @@ class ClientChannelFilter::LoadBalancedCall
// it will be queued instead.) // it will be queued instead.)
// - The pick completed successfully. A connected subchannel is // - The pick completed successfully. A connected subchannel is
// stored and an OK status will be returned. // stored and an OK status will be returned.
absl::optional<absl::Status> PickSubchannel(bool was_queued); std::optional<absl::Status> PickSubchannel(bool was_queued);
void RecordCallCompletion(absl::Status status, void RecordCallCompletion(absl::Status status,
grpc_metadata_batch* recv_trailing_metadata, grpc_metadata_batch* recv_trailing_metadata,
@ -431,6 +430,11 @@ class ClientChannelFilter::LoadBalancedCall
ABSL_EXCLUSIVE_LOCKS_REQUIRED(&ClientChannelFilter::lb_mu_) = 0; ABSL_EXCLUSIVE_LOCKS_REQUIRED(&ClientChannelFilter::lb_mu_) = 0;
ClientChannelFilter* chand_; ClientChannelFilter* chand_;
// When we start a new attempt for a call, we might not have cleaned up the
// previous attempt yet leading to a situation where we have two active call
// attempt tracers, and so we cannot rely on the arena to give us the right
// tracer when performing cleanup.
ClientCallTracer::CallAttemptTracer* call_attempt_tracer_;
absl::AnyInvocable<void()> on_commit_; absl::AnyInvocable<void()> on_commit_;
@ -534,7 +538,7 @@ class ClientChannelFilter::FilterBasedLoadBalancedCall final
CallCombiner* call_combiner_; CallCombiner* call_combiner_;
grpc_polling_entity* pollent_; grpc_polling_entity* pollent_;
grpc_closure* on_call_destruction_complete_; grpc_closure* on_call_destruction_complete_;
absl::optional<Slice> peer_string_; std::optional<Slice> peer_string_;
// Set when we get a cancel_stream op. // Set when we get a cancel_stream op.
grpc_error_handle cancel_error_; grpc_error_handle cancel_error_;

View File

@ -19,7 +19,8 @@
#include <grpc/impl/channel_arg_names.h> #include <grpc/impl/channel_arg_names.h>
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include "absl/types/optional.h" #include <optional>
#include "src/core/client_channel/client_channel_filter.h" #include "src/core/client_channel/client_channel_filter.h"
#include "src/core/client_channel/client_channel_service_config.h" #include "src/core/client_channel/client_channel_service_config.h"
#include "src/core/client_channel/retry_service_config.h" #include "src/core/client_channel/retry_service_config.h"

View File

@ -19,13 +19,13 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <map> #include <map>
#include <optional>
#include <utility> #include <utility>
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/strings/ascii.h" #include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "src/core/load_balancing/lb_policy_registry.h" #include "src/core/load_balancing/lb_policy_registry.h"
// As per the retry design, we do not allow more than 5 retry attempts. // As per the retry design, we do not allow more than 5 retry attempts.

View File

@ -21,10 +21,10 @@
#include <stddef.h> #include <stddef.h>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/load_balancing/lb_policy.h" #include "src/core/load_balancing/lb_policy.h"
@ -50,7 +50,7 @@ class ClientChannelGlobalParsedConfig final
return parsed_deprecated_lb_policy_; return parsed_deprecated_lb_policy_;
} }
const absl::optional<std::string>& health_check_service_name() const { const std::optional<std::string>& health_check_service_name() const {
return health_check_config_.service_name; return health_check_config_.service_name;
} }
@ -60,7 +60,7 @@ class ClientChannelGlobalParsedConfig final
private: private:
struct HealthCheckConfig { struct HealthCheckConfig {
absl::optional<std::string> service_name; std::optional<std::string> service_name;
static const JsonLoaderInterface* JsonLoader(const JsonArgs&); static const JsonLoaderInterface* JsonLoader(const JsonArgs&);
}; };
@ -75,13 +75,13 @@ class ClientChannelMethodParsedConfig final
public: public:
Duration timeout() const { return timeout_; } Duration timeout() const { return timeout_; }
absl::optional<bool> wait_for_ready() const { return wait_for_ready_; } std::optional<bool> wait_for_ready() const { return wait_for_ready_; }
static const JsonLoaderInterface* JsonLoader(const JsonArgs&); static const JsonLoaderInterface* JsonLoader(const JsonArgs&);
private: private:
Duration timeout_; Duration timeout_;
absl::optional<bool> wait_for_ready_; std::optional<bool> wait_for_ready_;
}; };
class ClientChannelServiceConfigParser final class ClientChannelServiceConfigParser final

View File

@ -70,7 +70,7 @@ void DirectChannel::GetInfo(const grpc_channel_info*) {
grpc_call* DirectChannel::CreateCall( grpc_call* DirectChannel::CreateCall(
grpc_call* parent_call, uint32_t propagation_mask, grpc_call* parent_call, uint32_t propagation_mask,
grpc_completion_queue* cq, grpc_pollset_set* /*pollset_set_alternative*/, grpc_completion_queue* cq, grpc_pollset_set* /*pollset_set_alternative*/,
Slice path, absl::optional<Slice> authority, Timestamp deadline, Slice path, std::optional<Slice> authority, Timestamp deadline,
bool /*registered_method*/) { bool /*registered_method*/) {
auto arena = call_arena_allocator()->MakeArena(); auto arena = call_arena_allocator()->MakeArena();
arena->SetContext<grpc_event_engine::experimental::EventEngine>( arena->SetContext<grpc_event_engine::experimental::EventEngine>(

View File

@ -61,7 +61,7 @@ class DirectChannel final : public Channel {
grpc_call* CreateCall(grpc_call* parent_call, uint32_t propagation_mask, grpc_call* CreateCall(grpc_call* parent_call, uint32_t propagation_mask,
grpc_completion_queue* cq, grpc_completion_queue* cq,
grpc_pollset_set* pollset_set_alternative, Slice path, grpc_pollset_set* pollset_set_alternative, Slice path,
absl::optional<Slice> authority, Timestamp deadline, std::optional<Slice> authority, Timestamp deadline,
bool registered_method) override; bool registered_method) override;
grpc_event_engine::experimental::EventEngine* event_engine() const override { grpc_event_engine::experimental::EventEngine* event_engine() const override {
return event_engine_.get(); return event_engine_.get();

View File

@ -54,9 +54,9 @@ class Encoder {
} // namespace } // namespace
absl::optional<absl::string_view> LbMetadata::Lookup( std::optional<absl::string_view> LbMetadata::Lookup(absl::string_view key,
absl::string_view key, std::string* buffer) const { std::string* buffer) const {
if (batch_ == nullptr) return absl::nullopt; if (batch_ == nullptr) return std::nullopt;
return batch_->GetStringValue(key, buffer); return batch_->GetStringValue(key, buffer);
} }
@ -75,10 +75,9 @@ LbMetadata::TestOnlyCopyToVector() const {
void MetadataMutationHandler::Apply( void MetadataMutationHandler::Apply(
LoadBalancingPolicy::MetadataMutations& metadata_mutations, LoadBalancingPolicy::MetadataMutations& metadata_mutations,
grpc_metadata_batch* metadata) { grpc_metadata_batch* metadata) {
for (auto& p : metadata_mutations.metadata_) { for (auto& [key, value_slice] : metadata_mutations.metadata_) {
absl::string_view key = p.first; Slice& value = grpc_event_engine::experimental::internal::SliceCast<Slice>(
Slice& value = value_slice);
grpc_event_engine::experimental::internal::SliceCast<Slice>(p.second);
// TODO(roth): Should we prevent this from setting special keys like // TODO(roth): Should we prevent this from setting special keys like
// :authority, :path, content-type, etc? // :authority, :path, content-type, etc?
metadata->Remove(key); metadata->Remove(key);
@ -92,7 +91,7 @@ void MetadataMutationHandler::Apply(
continue; continue;
} }
metadata->Append(key, std::move(value), metadata->Append(key, std::move(value),
[key](absl::string_view error, const Slice& value) { [key = key](absl::string_view error, const Slice& value) {
LOG(ERROR) << error << " key:" << key LOG(ERROR) << error << " key:" << key
<< " value:" << value.as_string_view(); << " value:" << value.as_string_view();
}); });

View File

@ -17,11 +17,11 @@
#include <grpc/event_engine/slice.h> #include <grpc/event_engine/slice.h>
#include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/lib/transport/metadata_batch.h" #include "src/core/lib/transport/metadata_batch.h"
#include "src/core/load_balancing/lb_policy.h" #include "src/core/load_balancing/lb_policy.h"
@ -31,7 +31,7 @@ class LbMetadata : public LoadBalancingPolicy::MetadataInterface {
public: public:
explicit LbMetadata(grpc_metadata_batch* batch) : batch_(batch) {} explicit LbMetadata(grpc_metadata_batch* batch) : batch_(batch) {}
absl::optional<absl::string_view> Lookup(absl::string_view key, std::optional<absl::string_view> Lookup(absl::string_view key,
std::string* buffer) const override; std::string* buffer) const override;
std::vector<std::pair<std::string, std::string>> TestOnlyCopyToVector() const; std::vector<std::pair<std::string, std::string>> TestOnlyCopyToVector() const;

View File

@ -62,22 +62,22 @@ T HandlePickResult(
std::function<T(LoadBalancingPolicy::PickResult::Fail*)> fail_func, std::function<T(LoadBalancingPolicy::PickResult::Fail*)> fail_func,
std::function<T(LoadBalancingPolicy::PickResult::Drop*)> drop_func) { std::function<T(LoadBalancingPolicy::PickResult::Drop*)> drop_func) {
auto* complete_pick = auto* complete_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Complete>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Complete>(&result->result);
if (complete_pick != nullptr) { if (complete_pick != nullptr) {
return complete_func(complete_pick); return complete_func(complete_pick);
} }
auto* queue_pick = auto* queue_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Queue>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Queue>(&result->result);
if (queue_pick != nullptr) { if (queue_pick != nullptr) {
return queue_func(queue_pick); return queue_func(queue_pick);
} }
auto* fail_pick = auto* fail_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Fail>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Fail>(&result->result);
if (fail_pick != nullptr) { if (fail_pick != nullptr) {
return fail_func(fail_pick); return fail_func(fail_pick);
} }
auto* drop_pick = auto* drop_pick =
absl::get_if<LoadBalancingPolicy::PickResult::Drop>(&result->result); std::get_if<LoadBalancingPolicy::PickResult::Drop>(&result->result);
CHECK(drop_pick != nullptr); CHECK(drop_pick != nullptr);
return drop_func(drop_pick); return drop_func(drop_pick);
} }

View File

@ -19,11 +19,11 @@
#include <grpc/event_engine/event_engine.h> #include <grpc/event_engine/event_engine.h>
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <optional>
#include <string> #include <string>
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/strings/strip.h" #include "absl/strings/strip.h"
#include "absl/types/optional.h"
#include "src/core/client_channel/client_channel_filter.h" #include "src/core/client_channel/client_channel_filter.h"
#include "src/core/client_channel/retry_filter_legacy_call_data.h" #include "src/core/client_channel/retry_filter_legacy_call_data.h"
#include "src/core/client_channel/retry_service_config.h" #include "src/core/client_channel/retry_service_config.h"

View File

@ -25,9 +25,9 @@
#include <stddef.h> #include <stddef.h>
#include <new> #include <new>
#include <optional>
#include "absl/log/check.h" #include "absl/log/check.h"
#include "absl/types/optional.h"
#include "src/core/client_channel/client_channel_filter.h" #include "src/core/client_channel/client_channel_filter.h"
#include "src/core/client_channel/retry_service_config.h" #include "src/core/client_channel/retry_service_config.h"
#include "src/core/client_channel/retry_throttle.h" #include "src/core/client_channel/retry_throttle.h"

View File

@ -154,7 +154,6 @@ RetryFilter::LegacyCallData::CallAttempt::CallAttempt(
Ref(DEBUG_LOCATION, "OnPerAttemptRecvTimer").release(); Ref(DEBUG_LOCATION, "OnPerAttemptRecvTimer").release();
per_attempt_recv_timer_handle_ = calld_->chand_->event_engine()->RunAfter( per_attempt_recv_timer_handle_ = calld_->chand_->event_engine()->RunAfter(
per_attempt_recv_timeout, [this] { per_attempt_recv_timeout, [this] {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
OnPerAttemptRecvTimer(); OnPerAttemptRecvTimer();
}); });
@ -529,8 +528,8 @@ void RetryFilter::LegacyCallData::CallAttempt::CancelFromSurface(
} }
bool RetryFilter::LegacyCallData::CallAttempt::ShouldRetry( bool RetryFilter::LegacyCallData::CallAttempt::ShouldRetry(
absl::optional<grpc_status_code> status, std::optional<grpc_status_code> status,
absl::optional<Duration> server_pushback) { std::optional<Duration> server_pushback) {
// If no retry policy, don't retry. // If no retry policy, don't retry.
if (calld_->retry_policy_ == nullptr) return false; if (calld_->retry_policy_ == nullptr) return false;
// Check status. // Check status.
@ -657,12 +656,12 @@ void RetryFilter::LegacyCallData::CallAttempt::OnPerAttemptRecvTimerLocked(
StatusIntProperty::kRpcStatus, GRPC_STATUS_CANCELLED), StatusIntProperty::kRpcStatus, GRPC_STATUS_CANCELLED),
&closures); &closures);
// Check whether we should retry. // Check whether we should retry.
if (call_attempt->ShouldRetry(/*status=*/absl::nullopt, if (call_attempt->ShouldRetry(/*status=*/std::nullopt,
/*server_pushback_ms=*/absl::nullopt)) { /*server_pushback_ms=*/std::nullopt)) {
// Mark current attempt as abandoned. // Mark current attempt as abandoned.
call_attempt->Abandon(); call_attempt->Abandon();
// We are retrying. Start backoff timer. // We are retrying. Start backoff timer.
calld->StartRetryTimer(/*server_pushback=*/absl::nullopt); calld->StartRetryTimer(/*server_pushback=*/std::nullopt);
} else { } else {
// Not retrying, so commit the call. // Not retrying, so commit the call.
calld->RetryCommit(call_attempt); calld->RetryCommit(call_attempt);
@ -953,9 +952,9 @@ namespace {
// and error. // and error.
void GetCallStatus( void GetCallStatus(
Timestamp deadline, grpc_metadata_batch* md_batch, grpc_error_handle error, Timestamp deadline, grpc_metadata_batch* md_batch, grpc_error_handle error,
grpc_status_code* status, absl::optional<Duration>* server_pushback, grpc_status_code* status, std::optional<Duration>* server_pushback,
bool* is_lb_drop, bool* is_lb_drop,
absl::optional<GrpcStreamNetworkState::ValueType>* stream_network_state) { std::optional<GrpcStreamNetworkState::ValueType>* stream_network_state) {
if (!error.ok()) { if (!error.ok()) {
grpc_error_get_status(error, deadline, status, nullptr, nullptr, nullptr); grpc_error_get_status(error, deadline, status, nullptr, nullptr, nullptr);
intptr_t value = 0; intptr_t value = 0;
@ -1092,9 +1091,9 @@ void RetryFilter::LegacyCallData::CallAttempt::BatchData::
call_attempt->MaybeCancelPerAttemptRecvTimer(); call_attempt->MaybeCancelPerAttemptRecvTimer();
// Get the call's status and check for server pushback metadata. // Get the call's status and check for server pushback metadata.
grpc_status_code status = GRPC_STATUS_OK; grpc_status_code status = GRPC_STATUS_OK;
absl::optional<Duration> server_pushback; std::optional<Duration> server_pushback;
bool is_lb_drop = false; bool is_lb_drop = false;
absl::optional<GrpcStreamNetworkState::ValueType> stream_network_state; std::optional<GrpcStreamNetworkState::ValueType> stream_network_state;
grpc_metadata_batch* md_batch = grpc_metadata_batch* md_batch =
batch_data->batch_.payload->recv_trailing_metadata.recv_trailing_metadata; batch_data->batch_.payload->recv_trailing_metadata.recv_trailing_metadata;
GetCallStatus(calld->deadline_, md_batch, error, &status, &server_pushback, GetCallStatus(calld->deadline_, md_batch, error, &status, &server_pushback,
@ -1880,7 +1879,7 @@ void RetryFilter::LegacyCallData::RetryCommit(CallAttempt* call_attempt) {
} }
void RetryFilter::LegacyCallData::StartRetryTimer( void RetryFilter::LegacyCallData::StartRetryTimer(
absl::optional<Duration> server_pushback) { std::optional<Duration> server_pushback) {
// Reset call attempt. // Reset call attempt.
call_attempt_.reset(DEBUG_LOCATION, "StartRetryTimer"); call_attempt_.reset(DEBUG_LOCATION, "StartRetryTimer");
// Compute backoff delay. // Compute backoff delay.
@ -1899,7 +1898,6 @@ void RetryFilter::LegacyCallData::StartRetryTimer(
GRPC_CALL_STACK_REF(owning_call_, "OnRetryTimer"); GRPC_CALL_STACK_REF(owning_call_, "OnRetryTimer");
retry_timer_handle_ = retry_timer_handle_ =
chand_->event_engine()->RunAfter(next_attempt_timeout, [this] { chand_->event_engine()->RunAfter(next_attempt_timeout, [this] {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
OnRetryTimer(); OnRetryTimer();
}); });

View File

@ -22,11 +22,11 @@
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <optional>
#include <utility> #include <utility>
#include "absl/container/inlined_vector.h" #include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h" #include "absl/functional/any_invocable.h"
#include "absl/types/optional.h"
#include "src/core/client_channel/client_channel_filter.h" #include "src/core/client_channel/client_channel_filter.h"
#include "src/core/client_channel/retry_filter.h" #include "src/core/client_channel/retry_filter.h"
#include "src/core/client_channel/retry_service_config.h" #include "src/core/client_channel/retry_service_config.h"
@ -241,8 +241,8 @@ class RetryFilter::LegacyCallData final {
void MaybeSwitchToFastPath(); void MaybeSwitchToFastPath();
// Returns true if the call should be retried. // Returns true if the call should be retried.
bool ShouldRetry(absl::optional<grpc_status_code> status, bool ShouldRetry(std::optional<grpc_status_code> status,
absl::optional<Duration> server_pushback_ms); std::optional<Duration> server_pushback_ms);
// Abandons the call attempt. Unrefs any deferred batches. // Abandons the call attempt. Unrefs any deferred batches.
void Abandon(); void Abandon();
@ -256,7 +256,7 @@ class RetryFilter::LegacyCallData final {
bool lb_call_committed_ = false; bool lb_call_committed_ = false;
grpc_closure on_per_attempt_recv_timer_; grpc_closure on_per_attempt_recv_timer_;
absl::optional<grpc_event_engine::experimental::EventEngine::TaskHandle> std::optional<grpc_event_engine::experimental::EventEngine::TaskHandle>
per_attempt_recv_timer_handle_; per_attempt_recv_timer_handle_;
// BatchData.batch.payload points to this. // BatchData.batch.payload points to this.
@ -273,7 +273,7 @@ class RetryFilter::LegacyCallData final {
bool trailing_metadata_available_ = false; bool trailing_metadata_available_ = false;
// For intercepting recv_message. // For intercepting recv_message.
grpc_closure recv_message_ready_; grpc_closure recv_message_ready_;
absl::optional<SliceBuffer> recv_message_; std::optional<SliceBuffer> recv_message_;
uint32_t recv_message_flags_; uint32_t recv_message_flags_;
// For intercepting recv_trailing_metadata. // For intercepting recv_trailing_metadata.
grpc_metadata_batch recv_trailing_metadata_; grpc_metadata_batch recv_trailing_metadata_;
@ -352,7 +352,7 @@ class RetryFilter::LegacyCallData final {
// Starts a timer to retry after appropriate back-off. // Starts a timer to retry after appropriate back-off.
// If server_pushback is nullopt, retry_backoff_ is used. // If server_pushback is nullopt, retry_backoff_ is used.
void StartRetryTimer(absl::optional<Duration> server_pushback); void StartRetryTimer(std::optional<Duration> server_pushback);
void OnRetryTimer(); void OnRetryTimer();
static void OnRetryTimerLocked(void* arg, grpc_error_handle /*error*/); static void OnRetryTimerLocked(void* arg, grpc_error_handle /*error*/);
@ -410,7 +410,7 @@ class RetryFilter::LegacyCallData final {
bool retry_codepath_started_ : 1; bool retry_codepath_started_ : 1;
bool sent_transparent_retry_not_seen_by_server_ : 1; bool sent_transparent_retry_not_seen_by_server_ : 1;
int num_attempts_completed_ = 0; int num_attempts_completed_ = 0;
absl::optional<grpc_event_engine::experimental::EventEngine::TaskHandle> std::optional<grpc_event_engine::experimental::EventEngine::TaskHandle>
retry_timer_handle_; retry_timer_handle_;
grpc_closure retry_closure_; grpc_closure retry_closure_;

View File

@ -55,14 +55,14 @@ RetryState::RetryState(
? Duration::Zero() ? Duration::Zero()
: retry_policy_->max_backoff())) {} : retry_policy_->max_backoff())) {}
absl::optional<Duration> RetryState::ShouldRetry( std::optional<Duration> RetryState::ShouldRetry(
const ServerMetadata& md, bool committed, const ServerMetadata& md, bool committed,
absl::FunctionRef<std::string()> lazy_attempt_debug_string) { absl::FunctionRef<std::string()> lazy_attempt_debug_string) {
// If no retry policy, don't retry. // If no retry policy, don't retry.
if (retry_policy_ == nullptr) { if (retry_policy_ == nullptr) {
GRPC_TRACE_LOG(retry, INFO) GRPC_TRACE_LOG(retry, INFO)
<< lazy_attempt_debug_string() << " no retry policy"; << lazy_attempt_debug_string() << " no retry policy";
return absl::nullopt; return std::nullopt;
} }
const auto status = md.get(GrpcStatusMetadata()); const auto status = md.get(GrpcStatusMetadata());
if (status.has_value()) { if (status.has_value()) {
@ -72,14 +72,14 @@ absl::optional<Duration> RetryState::ShouldRetry(
} }
GRPC_TRACE_LOG(retry, INFO) GRPC_TRACE_LOG(retry, INFO)
<< lazy_attempt_debug_string() << " call succeeded"; << lazy_attempt_debug_string() << " call succeeded";
return absl::nullopt; return std::nullopt;
} }
// Status is not OK. Check whether the status is retryable. // Status is not OK. Check whether the status is retryable.
if (!retry_policy_->retryable_status_codes().Contains(*status)) { if (!retry_policy_->retryable_status_codes().Contains(*status)) {
GRPC_TRACE_LOG(retry, INFO) << lazy_attempt_debug_string() << ": status " GRPC_TRACE_LOG(retry, INFO) << lazy_attempt_debug_string() << ": status "
<< grpc_status_code_to_string(*status) << grpc_status_code_to_string(*status)
<< " not configured as retryable"; << " not configured as retryable";
return absl::nullopt; return std::nullopt;
} }
} }
// Record the failure and check whether retries are throttled. // Record the failure and check whether retries are throttled.
@ -93,13 +93,13 @@ absl::optional<Duration> RetryState::ShouldRetry(
!retry_throttle_data_->RecordFailure()) { !retry_throttle_data_->RecordFailure()) {
GRPC_TRACE_LOG(retry, INFO) GRPC_TRACE_LOG(retry, INFO)
<< lazy_attempt_debug_string() << " retries throttled"; << lazy_attempt_debug_string() << " retries throttled";
return absl::nullopt; return std::nullopt;
} }
// Check whether the call is committed. // Check whether the call is committed.
if (committed) { if (committed) {
GRPC_TRACE_LOG(retry, INFO) GRPC_TRACE_LOG(retry, INFO)
<< lazy_attempt_debug_string() << " retries already committed"; << lazy_attempt_debug_string() << " retries already committed";
return absl::nullopt; return std::nullopt;
} }
// Check whether we have retries remaining. // Check whether we have retries remaining.
++num_attempts_completed_; ++num_attempts_completed_;
@ -107,14 +107,14 @@ absl::optional<Duration> RetryState::ShouldRetry(
GRPC_TRACE_LOG(retry, INFO) GRPC_TRACE_LOG(retry, INFO)
<< lazy_attempt_debug_string() << " exceeded " << lazy_attempt_debug_string() << " exceeded "
<< retry_policy_->max_attempts() << " retry attempts"; << retry_policy_->max_attempts() << " retry attempts";
return absl::nullopt; return std::nullopt;
} }
// Check server push-back. // Check server push-back.
const auto server_pushback = md.get(GrpcRetryPushbackMsMetadata()); const auto server_pushback = md.get(GrpcRetryPushbackMsMetadata());
if (server_pushback.has_value() && server_pushback < Duration::Zero()) { if (server_pushback.has_value() && server_pushback < Duration::Zero()) {
GRPC_TRACE_LOG(retry, INFO) << lazy_attempt_debug_string() GRPC_TRACE_LOG(retry, INFO) << lazy_attempt_debug_string()
<< " not retrying due to server push-back"; << " not retrying due to server push-back";
return absl::nullopt; return std::nullopt;
} }
// We should retry. // We should retry.
Duration next_attempt_timeout; Duration next_attempt_timeout;
@ -298,8 +298,9 @@ auto RetryInterceptor::Attempt::ServerToClientGotInitialMetadata(
GRPC_TRACE_LOG(retry, INFO) GRPC_TRACE_LOG(retry, INFO)
<< call->DebugTag() << " got server message " << call->DebugTag() << " got server message "
<< message->DebugString(); << message->DebugString();
return call->call_handler()->SpawnPushMessage( call->call_handler()->SpawnPushMessage(
std::move(message)); std::move(message));
return Success{};
}), }),
initiator_.PullServerTrailingMetadata(), initiator_.PullServerTrailingMetadata(),
[call = call_](ServerMetadataHandle md) { [call = call_](ServerMetadataHandle md) {
@ -346,7 +347,7 @@ auto RetryInterceptor::Attempt::ServerToClientGotTrailersOnlyResponse() {
auto RetryInterceptor::Attempt::ServerToClient() { auto RetryInterceptor::Attempt::ServerToClient() {
return TrySeq( return TrySeq(
initiator_.PullServerInitialMetadata(), initiator_.PullServerInitialMetadata(),
[self = Ref()](absl::optional<ServerMetadataHandle> metadata) { [self = Ref()](std::optional<ServerMetadataHandle> metadata) {
const bool has_md = metadata.has_value(); const bool has_md = metadata.has_value();
return If( return If(
has_md, has_md,
@ -385,9 +386,10 @@ auto RetryInterceptor::Attempt::ClientToServer() {
self->call_->call_handler()->AddChildCall(self->initiator_); self->call_->call_handler()->AddChildCall(self->initiator_);
self->initiator_.SpawnGuarded( self->initiator_.SpawnGuarded(
"server_to_client", [self]() { return self->ServerToClient(); }); "server_to_client", [self]() { return self->ServerToClient(); });
return ForEach( return ForEach(MessagesFrom(&self->reader_),
MessagesFrom(&self->reader_), [self](MessageHandle message) { [self](MessageHandle message) {
return self->initiator_.SpawnPushMessage(std::move(message)); self->initiator_.SpawnPushMessage(std::move(message));
return Success{};
}); });
}); });
} }

View File

@ -34,7 +34,7 @@ class RetryState {
// if nullopt --> commit & don't retry // if nullopt --> commit & don't retry
// if duration --> retry after duration // if duration --> retry after duration
absl::optional<Duration> ShouldRetry( std::optional<Duration> ShouldRetry(
const ServerMetadata& md, bool committed, const ServerMetadata& md, bool committed,
absl::FunctionRef<std::string()> lazy_attempt_debug_string); absl::FunctionRef<std::string()> lazy_attempt_debug_string);
int num_attempts_completed() const { return num_attempts_completed_; } int num_attempts_completed() const { return num_attempts_completed_; }
@ -90,7 +90,7 @@ class RetryInterceptor : public Interceptor {
RetryInterceptor* interceptor() { return interceptor_.get(); } RetryInterceptor* interceptor() { return interceptor_.get(); }
// if nullopt --> commit & don't retry // if nullopt --> commit & don't retry
// if duration --> retry after duration // if duration --> retry after duration
absl::optional<Duration> ShouldRetry( std::optional<Duration> ShouldRetry(
const ServerMetadata& md, const ServerMetadata& md,
absl::FunctionRef<std::string()> lazy_attempt_debug_string) { absl::FunctionRef<std::string()> lazy_attempt_debug_string) {
return retry_state_.ShouldRetry(md, request_buffer_.committed(), return retry_state_.ShouldRetry(md, request_buffer_.committed(),

View File

@ -22,6 +22,7 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <map> #include <map>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -29,7 +30,6 @@
#include "absl/log/log.h" #include "absl/log/log.h"
#include "absl/strings/numbers.h" #include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/status_util.h" #include "src/core/lib/channel/status_util.h"

View File

@ -22,9 +22,9 @@
#include <stdint.h> #include <stdint.h>
#include <memory> #include <memory>
#include <optional>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/status_util.h" #include "src/core/lib/channel/status_util.h"
@ -61,7 +61,7 @@ class RetryMethodConfig final : public ServiceConfigParser::ParsedConfig {
StatusCodeSet retryable_status_codes() const { StatusCodeSet retryable_status_codes() const {
return retryable_status_codes_; return retryable_status_codes_;
} }
absl::optional<Duration> per_attempt_recv_timeout() const { std::optional<Duration> per_attempt_recv_timeout() const {
return per_attempt_recv_timeout_; return per_attempt_recv_timeout_;
} }
@ -88,7 +88,7 @@ class RetryMethodConfig final : public ServiceConfigParser::ParsedConfig {
Duration max_backoff_; Duration max_backoff_;
float backoff_multiplier_ = 0; float backoff_multiplier_ = 0;
StatusCodeSet retryable_status_codes_; StatusCodeSet retryable_status_codes_;
absl::optional<Duration> per_attempt_recv_timeout_; std::optional<Duration> per_attempt_recv_timeout_;
}; };
class RetryServiceConfigParser final : public ServiceConfigParser::Parser { class RetryServiceConfigParser final : public ServiceConfigParser::Parser {

View File

@ -26,6 +26,7 @@
#include <algorithm> #include <algorithm>
#include <memory> #include <memory>
#include <new> #include <new>
#include <optional>
#include <utility> #include <utility>
#include "absl/log/check.h" #include "absl/log/check.h"
@ -34,7 +35,6 @@
#include "absl/strings/cord.h" #include "absl/strings/cord.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/channelz/channel_trace.h" #include "src/core/channelz/channel_trace.h"
#include "src/core/channelz/channelz.h" #include "src/core/channelz/channelz.h"
#include "src/core/client_channel/client_channel_internal.h" #include "src/core/client_channel/client_channel_internal.h"
@ -431,8 +431,6 @@ class Subchannel::ConnectedSubchannelStateWatcher final
c->backoff_.Reset(); c->backoff_.Reset();
} }
} }
// Drain any connectivity state notifications after releasing the mutex.
c->work_serializer_.DrainQueue();
} }
WeakRefCountedPtr<Subchannel> subchannel_; WeakRefCountedPtr<Subchannel> subchannel_;
@ -444,7 +442,7 @@ class Subchannel::ConnectedSubchannelStateWatcher final
void Subchannel::ConnectivityStateWatcherList::AddWatcherLocked( void Subchannel::ConnectivityStateWatcherList::AddWatcherLocked(
RefCountedPtr<ConnectivityStateWatcherInterface> watcher) { RefCountedPtr<ConnectivityStateWatcherInterface> watcher) {
watchers_.insert(std::make_pair(watcher.get(), std::move(watcher))); watchers_.insert(std::move(watcher));
} }
void Subchannel::ConnectivityStateWatcherList::RemoveWatcherLocked( void Subchannel::ConnectivityStateWatcherList::RemoveWatcherLocked(
@ -454,14 +452,12 @@ void Subchannel::ConnectivityStateWatcherList::RemoveWatcherLocked(
void Subchannel::ConnectivityStateWatcherList::NotifyLocked( void Subchannel::ConnectivityStateWatcherList::NotifyLocked(
grpc_connectivity_state state, const absl::Status& status) { grpc_connectivity_state state, const absl::Status& status) {
for (const auto& p : watchers_) { for (const auto& watcher : watchers_) {
subchannel_->work_serializer_.Schedule( subchannel_->work_serializer_.Run([watcher = watcher->Ref(), state,
[watcher = p.second->Ref(), state, status]() mutable { status]() mutable {
auto* watcher_ptr = watcher.get(); auto* watcher_ptr = watcher.get();
watcher_ptr->OnConnectivityStateChange(std::move(watcher), state, watcher_ptr->OnConnectivityStateChange(std::move(watcher), state, status);
status); });
},
DEBUG_LOCATION);
} }
} }
@ -473,7 +469,7 @@ namespace {
BackOff::Options ParseArgsForBackoffValues(const ChannelArgs& args, BackOff::Options ParseArgsForBackoffValues(const ChannelArgs& args,
Duration* min_connect_timeout) { Duration* min_connect_timeout) {
const absl::optional<Duration> fixed_reconnect_backoff = const std::optional<Duration> fixed_reconnect_backoff =
args.GetDurationFromIntMillis("grpc.testing.fixed_reconnect_backoff_ms"); args.GetDurationFromIntMillis("grpc.testing.fixed_reconnect_backoff_ms");
if (fixed_reconnect_backoff.has_value()) { if (fixed_reconnect_backoff.has_value()) {
const Duration backoff = const Duration backoff =
@ -611,13 +607,12 @@ channelz::SubchannelNode* Subchannel::channelz_node() {
void Subchannel::WatchConnectivityState( void Subchannel::WatchConnectivityState(
RefCountedPtr<ConnectivityStateWatcherInterface> watcher) { RefCountedPtr<ConnectivityStateWatcherInterface> watcher) {
{
MutexLock lock(&mu_); MutexLock lock(&mu_);
grpc_pollset_set* interested_parties = watcher->interested_parties(); grpc_pollset_set* interested_parties = watcher->interested_parties();
if (interested_parties != nullptr) { if (interested_parties != nullptr) {
grpc_pollset_set_add_pollset_set(pollset_set_, interested_parties); grpc_pollset_set_add_pollset_set(pollset_set_, interested_parties);
} }
work_serializer_.Schedule( work_serializer_.Run(
[watcher = watcher->Ref(), state = state_, status = status_]() mutable { [watcher = watcher->Ref(), state = state_, status = status_]() mutable {
auto* watcher_ptr = watcher.get(); auto* watcher_ptr = watcher.get();
watcher_ptr->OnConnectivityStateChange(std::move(watcher), state, watcher_ptr->OnConnectivityStateChange(std::move(watcher), state,
@ -626,13 +621,9 @@ void Subchannel::WatchConnectivityState(
DEBUG_LOCATION); DEBUG_LOCATION);
watcher_list_.AddWatcherLocked(std::move(watcher)); watcher_list_.AddWatcherLocked(std::move(watcher));
} }
// Drain any connectivity state notifications after releasing the mutex.
work_serializer_.DrainQueue();
}
void Subchannel::CancelConnectivityStateWatch( void Subchannel::CancelConnectivityStateWatch(
ConnectivityStateWatcherInterface* watcher) { ConnectivityStateWatcherInterface* watcher) {
{
MutexLock lock(&mu_); MutexLock lock(&mu_);
grpc_pollset_set* interested_parties = watcher->interested_parties(); grpc_pollset_set* interested_parties = watcher->interested_parties();
if (interested_parties != nullptr) { if (interested_parties != nullptr) {
@ -640,29 +631,19 @@ void Subchannel::CancelConnectivityStateWatch(
} }
watcher_list_.RemoveWatcherLocked(watcher); watcher_list_.RemoveWatcherLocked(watcher);
} }
// Drain any connectivity state notifications after releasing the mutex.
// (Shouldn't actually be necessary in this case, but better safe than
// sorry.)
work_serializer_.DrainQueue();
}
void Subchannel::RequestConnection() { void Subchannel::RequestConnection() {
{
MutexLock lock(&mu_); MutexLock lock(&mu_);
if (state_ == GRPC_CHANNEL_IDLE) { if (state_ == GRPC_CHANNEL_IDLE) {
StartConnectingLocked(); StartConnectingLocked();
} }
} }
// Drain any connectivity state notifications after releasing the mutex.
work_serializer_.DrainQueue();
}
void Subchannel::ResetBackoff() { void Subchannel::ResetBackoff() {
// Hold a ref to ensure cancellation and subsequent deletion of the closure // Hold a ref to ensure cancellation and subsequent deletion of the closure
// does not eliminate the last ref and destroy the Subchannel before the // does not eliminate the last ref and destroy the Subchannel before the
// method returns. // method returns.
auto self = WeakRef(DEBUG_LOCATION, "ResetBackoff"); auto self = WeakRef(DEBUG_LOCATION, "ResetBackoff");
{
MutexLock lock(&mu_); MutexLock lock(&mu_);
backoff_.Reset(); backoff_.Reset();
if (state_ == GRPC_CHANNEL_TRANSIENT_FAILURE && if (state_ == GRPC_CHANNEL_TRANSIENT_FAILURE &&
@ -672,9 +653,6 @@ void Subchannel::ResetBackoff() {
next_attempt_time_ = Timestamp::Now(); next_attempt_time_ = Timestamp::Now();
} }
} }
// Drain any connectivity state notifications after releasing the mutex.
work_serializer_.DrainQueue();
}
void Subchannel::Orphaned() { void Subchannel::Orphaned() {
// The subchannel_pool is only used once here in this subchannel, so the // The subchannel_pool is only used once here in this subchannel, so the
@ -683,16 +661,12 @@ void Subchannel::Orphaned() {
subchannel_pool_->UnregisterSubchannel(key_, this); subchannel_pool_->UnregisterSubchannel(key_, this);
subchannel_pool_.reset(); subchannel_pool_.reset();
} }
{
MutexLock lock(&mu_); MutexLock lock(&mu_);
CHECK(!shutdown_); CHECK(!shutdown_);
shutdown_ = true; shutdown_ = true;
connector_.reset(); connector_.reset();
connected_subchannel_.reset(); connected_subchannel_.reset();
} }
// Drain any connectivity state notifications after releasing the mutex.
work_serializer_.DrainQueue();
}
void Subchannel::GetOrAddDataProducer( void Subchannel::GetOrAddDataProducer(
UniqueTypeName type, UniqueTypeName type,
@ -743,13 +717,9 @@ void Subchannel::SetConnectivityStateLocked(grpc_connectivity_state state,
} }
void Subchannel::OnRetryTimer() { void Subchannel::OnRetryTimer() {
{
MutexLock lock(&mu_); MutexLock lock(&mu_);
OnRetryTimerLocked(); OnRetryTimerLocked();
} }
// Drain any connectivity state notifications after releasing the mutex.
work_serializer_.DrainQueue();
}
void Subchannel::OnRetryTimerLocked() { void Subchannel::OnRetryTimerLocked() {
if (shutdown_) return; if (shutdown_) return;
@ -782,8 +752,6 @@ void Subchannel::OnConnectingFinished(void* arg, grpc_error_handle error) {
MutexLock lock(&c->mu_); MutexLock lock(&c->mu_);
c->OnConnectingFinishedLocked(error); c->OnConnectingFinishedLocked(error);
} }
// Drain any connectivity state notifications after releasing the mutex.
c->work_serializer_.DrainQueue();
c.reset(DEBUG_LOCATION, "Connect"); c.reset(DEBUG_LOCATION, "Connect");
} }
@ -810,7 +778,6 @@ void Subchannel::OnConnectingFinishedLocked(grpc_error_handle error) {
time_until_next_attempt, time_until_next_attempt,
[self = WeakRef(DEBUG_LOCATION, "RetryTimer")]() mutable { [self = WeakRef(DEBUG_LOCATION, "RetryTimer")]() mutable {
{ {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
self->OnRetryTimer(); self->OnRetryTimer();
// Subchannel deletion might require an active ExecCtx. So if // Subchannel deletion might require an active ExecCtx. So if

View File

@ -27,6 +27,7 @@
#include <memory> #include <memory>
#include "absl/base/thread_annotations.h" #include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h" #include "absl/status/status.h"
#include "src/core/client_channel/connector.h" #include "src/core/client_channel/connector.h"
#include "src/core/client_channel/subchannel_pool_interface.h" #include "src/core/client_channel/subchannel_pool_interface.h"
@ -307,10 +308,9 @@ class Subchannel final : public DualRefCounted<Subchannel> {
private: private:
Subchannel* subchannel_; Subchannel* subchannel_;
// TODO(roth): Once we can use C++-14 heterogeneous lookups, this can absl::flat_hash_set<RefCountedPtr<ConnectivityStateWatcherInterface>,
// be a set instead of a map. RefCountedPtrHash<ConnectivityStateWatcherInterface>,
std::map<ConnectivityStateWatcherInterface*, RefCountedPtrEq<ConnectivityStateWatcherInterface>>
RefCountedPtr<ConnectivityStateWatcherInterface>>
watchers_; watchers_;
}; };

View File

@ -140,7 +140,6 @@ void SubchannelStreamClient::StartRetryTimerLocked() {
} }
retry_timer_handle_ = event_engine_->RunAfter( retry_timer_handle_ = event_engine_->RunAfter(
timeout, [self = Ref(DEBUG_LOCATION, "health_retry_timer")]() mutable { timeout, [self = Ref(DEBUG_LOCATION, "health_retry_timer")]() mutable {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
self->OnRetryTimer(); self->OnRetryTimer();
self.reset(DEBUG_LOCATION, "health_retry_timer"); self.reset(DEBUG_LOCATION, "health_retry_timer");

View File

@ -25,11 +25,11 @@
#include <atomic> #include <atomic>
#include <memory> #include <memory>
#include <optional>
#include "absl/base/thread_annotations.h" #include "absl/base/thread_annotations.h"
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/client_channel/subchannel.h" #include "src/core/client_channel/subchannel.h"
#include "src/core/lib/iomgr/call_combiner.h" #include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/closure.h"
@ -172,7 +172,7 @@ class SubchannelStreamClient final
grpc_closure recv_initial_metadata_ready_; grpc_closure recv_initial_metadata_ready_;
// recv_message // recv_message
absl::optional<SliceBuffer> recv_message_; std::optional<SliceBuffer> recv_message_;
grpc_closure recv_message_ready_; grpc_closure recv_message_ready_;
std::atomic<bool> seen_response_{false}; std::atomic<bool> seen_response_{false};
@ -208,7 +208,7 @@ class SubchannelStreamClient final
// Call retry state. // Call retry state.
BackOff retry_backoff_ ABSL_GUARDED_BY(mu_); BackOff retry_backoff_ ABSL_GUARDED_BY(mu_);
absl::optional<grpc_event_engine::experimental::EventEngine::TaskHandle> std::optional<grpc_event_engine::experimental::EventEngine::TaskHandle>
retry_timer_handle_ ABSL_GUARDED_BY(mu_); retry_timer_handle_ ABSL_GUARDED_BY(mu_);
// A raw pointer will suffice since connected_subchannel_ holds a copy of the // A raw pointer will suffice since connected_subchannel_ holds a copy of the
// ChannelArgs which holds an std::shared_ptr of the EventEngine. // ChannelArgs which holds an std::shared_ptr of the EventEngine.

View File

@ -22,6 +22,7 @@
#include "absl/flags/flag.h" #include "absl/flags/flag.h"
#include "absl/strings/escaping.h" #include "absl/strings/escaping.h"
#include "absl/types/optional.h"
#include "src/core/config/load_config.h" #include "src/core/config/load_config.h"
#ifndef GPR_DEFAULT_LOG_VERBOSITY_STRING #ifndef GPR_DEFAULT_LOG_VERBOSITY_STRING

View File

@ -23,6 +23,7 @@
#include <stdint.h> #include <stdint.h>
#include <atomic> #include <atomic>
#include <optional>
#include <string> #include <string>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"

View File

@ -17,17 +17,18 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <stdio.h> #include <stdio.h>
#include <optional>
#include "absl/flags/marshalling.h" #include "absl/flags/marshalling.h"
#include "absl/log/check.h" #include "absl/log/check.h"
#include "absl/strings/numbers.h" #include "absl/strings/numbers.h"
#include "absl/strings/str_join.h" #include "absl/strings/str_join.h"
#include "absl/types/optional.h"
#include "src/core/util/env.h" #include "src/core/util/env.h"
namespace grpc_core { namespace grpc_core {
namespace { namespace {
absl::optional<std::string> LoadEnv(absl::string_view environment_variable) { std::optional<std::string> LoadEnv(absl::string_view environment_variable) {
return GetEnv(std::string(environment_variable).c_str()); return GetEnv(std::string(environment_variable).c_str());
} }
} // namespace } // namespace

View File

@ -18,12 +18,12 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <stdint.h> #include <stdint.h>
#include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
#include "absl/flags/flag.h" #include "absl/flags/flag.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace grpc_core { namespace grpc_core {

View File

@ -44,17 +44,10 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor BackendMetricFilter::Call::OnClientInitialMetadata;
const NoInterceptor BackendMetricFilter::Call::OnServerInitialMetadata;
const NoInterceptor BackendMetricFilter::Call::OnClientToServerMessage;
const NoInterceptor BackendMetricFilter::Call::OnClientToServerHalfClose;
const NoInterceptor BackendMetricFilter::Call::OnServerToClientMessage;
const NoInterceptor BackendMetricFilter::Call::OnFinalize;
namespace { namespace {
absl::optional<std::string> MaybeSerializeBackendMetrics( std::optional<std::string> MaybeSerializeBackendMetrics(
BackendMetricProvider* provider) { BackendMetricProvider* provider) {
if (provider == nullptr) return absl::nullopt; if (provider == nullptr) return std::nullopt;
BackendMetricData data = provider->GetBackendMetricData(); BackendMetricData data = provider->GetBackendMetricData();
upb::Arena arena; upb::Arena arena;
xds_data_orca_v3_OrcaLoadReport* response = xds_data_orca_v3_OrcaLoadReport* response =
@ -105,7 +98,7 @@ absl::optional<std::string> MaybeSerializeBackendMetrics(
has_data = true; has_data = true;
} }
if (!has_data) { if (!has_data) {
return absl::nullopt; return std::nullopt;
} }
size_t len; size_t len;
char* buf = char* buf =
@ -132,7 +125,7 @@ void BackendMetricFilter::Call::OnServerTrailingMetadata(ServerMetadata& md) {
<< "[" << this << "] No BackendMetricProvider."; << "[" << this << "] No BackendMetricProvider.";
return; return;
} }
absl::optional<std::string> serialized = MaybeSerializeBackendMetrics(ctx); std::optional<std::string> serialized = MaybeSerializeBackendMetrics(ctx);
if (serialized.has_value() && !serialized->empty()) { if (serialized.has_value() && !serialized->empty()) {
GRPC_TRACE_LOG(backend_metric_filter, INFO) GRPC_TRACE_LOG(backend_metric_filter, INFO)
<< "[" << this << "[" << this

View File

@ -17,10 +17,10 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <optional>
#include <string> #include <string>
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "src/core/ext/filters/backend_metrics/backend_metric_provider.h" #include "src/core/ext/filters/backend_metrics/backend_metric_provider.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_fwd.h" #include "src/core/lib/channel/channel_fwd.h"
@ -41,13 +41,13 @@ class BackendMetricFilter : public ImplementChannelFilter<BackendMetricFilter> {
class Call { class Call {
public: public:
static const NoInterceptor OnClientInitialMetadata; static inline const NoInterceptor OnClientInitialMetadata;
static const NoInterceptor OnServerInitialMetadata; static inline const NoInterceptor OnServerInitialMetadata;
void OnServerTrailingMetadata(ServerMetadata& md); void OnServerTrailingMetadata(ServerMetadata& md);
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
}; };
}; };

View File

@ -21,13 +21,13 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <functional> #include <functional>
#include <optional>
#include <utility> #include <utility>
#include "absl/base/thread_annotations.h" #include "absl/base/thread_annotations.h"
#include "absl/meta/type_traits.h" #include "absl/meta/type_traits.h"
#include "absl/random/random.h" #include "absl/random/random.h"
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/promise_based_filter.h" #include "src/core/lib/channel/promise_based_filter.h"

View File

@ -23,6 +23,7 @@
#include <algorithm> #include <algorithm>
#include <atomic> #include <atomic>
#include <functional> #include <functional>
#include <optional>
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
@ -34,7 +35,6 @@
#include "absl/strings/numbers.h" #include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/ext/filters/fault_injection/fault_injection_service_config_parser.h" #include "src/core/ext/filters/fault_injection/fault_injection_service_config_parser.h"
#include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/channel_stack.h"
@ -50,13 +50,6 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor FaultInjectionFilter::Call::OnServerInitialMetadata;
const NoInterceptor FaultInjectionFilter::Call::OnServerTrailingMetadata;
const NoInterceptor FaultInjectionFilter::Call::OnClientToServerMessage;
const NoInterceptor FaultInjectionFilter::Call::OnClientToServerHalfClose;
const NoInterceptor FaultInjectionFilter::Call::OnServerToClientMessage;
const NoInterceptor FaultInjectionFilter::Call::OnFinalize;
namespace { namespace {
std::atomic<uint32_t> g_active_faults{0}; std::atomic<uint32_t> g_active_faults{0};
@ -65,10 +58,10 @@ static_assert(
"the active fault counter needs to have a trivially destructible type"); "the active fault counter needs to have a trivially destructible type");
template <typename T> template <typename T>
auto AsInt(absl::string_view s) -> absl::optional<T> { auto AsInt(absl::string_view s) -> std::optional<T> {
T x; T x;
if (absl::SimpleAtoi(s, &x)) return x; if (absl::SimpleAtoi(s, &x)) return x;
return absl::nullopt; return std::nullopt;
} }
inline bool UnderFraction(absl::InsecureBitGen* rand_generator, inline bool UnderFraction(absl::InsecureBitGen* rand_generator,
@ -114,7 +107,7 @@ class FaultHandle {
class FaultInjectionFilter::InjectionDecision { class FaultInjectionFilter::InjectionDecision {
public: public:
InjectionDecision(uint32_t max_faults, Duration delay_time, InjectionDecision(uint32_t max_faults, Duration delay_time,
absl::optional<absl::Status> abort_request) std::optional<absl::Status> abort_request)
: max_faults_(max_faults), : max_faults_(max_faults),
delay_time_(delay_time), delay_time_(delay_time),
abort_request_(abort_request) {} abort_request_(abort_request) {}
@ -128,7 +121,7 @@ class FaultInjectionFilter::InjectionDecision {
uint32_t max_faults_; uint32_t max_faults_;
Duration delay_time_; Duration delay_time_;
absl::optional<absl::Status> abort_request_; std::optional<absl::Status> abort_request_;
FaultHandle active_fault_{false}; FaultHandle active_fault_{false};
}; };
@ -174,7 +167,7 @@ FaultInjectionFilter::MakeInjectionDecision(
// Shouldn't ever be null, but just in case, return a no-op decision. // Shouldn't ever be null, but just in case, return a no-op decision.
if (fi_policy == nullptr) { if (fi_policy == nullptr) {
return InjectionDecision(/*max_faults=*/0, /*delay_time=*/Duration::Zero(), return InjectionDecision(/*max_faults=*/0, /*delay_time=*/Duration::Zero(),
/*abort_request=*/absl::nullopt); /*abort_request=*/std::nullopt);
} }
grpc_status_code abort_code = fi_policy->abort_code; grpc_status_code abort_code = fi_policy->abort_code;
@ -240,10 +233,10 @@ FaultInjectionFilter::MakeInjectionDecision(
return InjectionDecision( return InjectionDecision(
fi_policy->max_faults, delay_request ? delay : Duration::Zero(), fi_policy->max_faults, delay_request ? delay : Duration::Zero(),
abort_request ? absl::optional<absl::Status>(absl::Status( abort_request ? std::optional<absl::Status>(absl::Status(
static_cast<absl::StatusCode>(abort_code), static_cast<absl::StatusCode>(abort_code),
fi_policy->abort_message)) fi_policy->abort_message))
: absl::nullopt); : std::nullopt);
} }
bool FaultInjectionFilter::InjectionDecision::HaveActiveFaultsQuota() const { bool FaultInjectionFilter::InjectionDecision::HaveActiveFaultsQuota() const {

View File

@ -55,12 +55,12 @@ class FaultInjectionFilter
public: public:
ArenaPromise<absl::Status> OnClientInitialMetadata( ArenaPromise<absl::Status> OnClientInitialMetadata(
ClientMetadata& md, FaultInjectionFilter* filter); ClientMetadata& md, FaultInjectionFilter* filter);
static const NoInterceptor OnServerInitialMetadata; static inline const NoInterceptor OnServerInitialMetadata;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
}; };
private: private:

View File

@ -18,9 +18,9 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <optional>
#include <vector> #include <vector>
#include "absl/types/optional.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/status_util.h" #include "src/core/lib/channel/status_util.h"

View File

@ -40,13 +40,6 @@ namespace grpc_core {
// GcpAuthenticationFilter::Call // GcpAuthenticationFilter::Call
// //
const NoInterceptor GcpAuthenticationFilter::Call::OnClientToServerMessage;
const NoInterceptor GcpAuthenticationFilter::Call::OnClientToServerHalfClose;
const NoInterceptor GcpAuthenticationFilter::Call::OnServerInitialMetadata;
const NoInterceptor GcpAuthenticationFilter::Call::OnServerToClientMessage;
const NoInterceptor GcpAuthenticationFilter::Call::OnServerTrailingMetadata;
const NoInterceptor GcpAuthenticationFilter::Call::OnFinalize;
absl::Status GcpAuthenticationFilter::Call::OnClientInitialMetadata( absl::Status GcpAuthenticationFilter::Call::OnClientInitialMetadata(
ClientMetadata& /*md*/, GcpAuthenticationFilter* filter) { ClientMetadata& /*md*/, GcpAuthenticationFilter* filter) {
// Get the cluster name chosen for this RPC. // Get the cluster name chosen for this RPC.

View File

@ -53,12 +53,12 @@ class GcpAuthenticationFilter
public: public:
absl::Status OnClientInitialMetadata(ClientMetadata& /*md*/, absl::Status OnClientInitialMetadata(ClientMetadata& /*md*/,
GcpAuthenticationFilter* filter); GcpAuthenticationFilter* filter);
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerInitialMetadata; static inline const NoInterceptor OnServerInitialMetadata;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
}; };
private: private:

View File

@ -18,9 +18,9 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <optional>
#include <vector> #include <vector>
#include "absl/types/optional.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
namespace grpc_core { namespace grpc_core {

View File

@ -20,11 +20,11 @@
#include <stddef.h> #include <stddef.h>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/service_config/service_config_parser.h" #include "src/core/service_config/service_config_parser.h"

View File

@ -25,6 +25,7 @@
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -35,7 +36,6 @@
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include "absl/strings/str_join.h" #include "absl/strings/str_join.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/promise/context.h" #include "src/core/lib/promise/context.h"
@ -51,11 +51,6 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor HttpClientFilter::Call::OnServerToClientMessage;
const NoInterceptor HttpClientFilter::Call::OnClientToServerMessage;
const NoInterceptor HttpClientFilter::Call::OnClientToServerHalfClose;
const NoInterceptor HttpClientFilter::Call::OnFinalize;
const grpc_channel_filter HttpClientFilter::kFilter = const grpc_channel_filter HttpClientFilter::kFilter =
MakePromiseBasedFilter<HttpClientFilter, FilterEndpoint::kClient, MakePromiseBasedFilter<HttpClientFilter, FilterEndpoint::kClient,
kFilterExaminesServerInitialMetadata>(); kFilterExaminesServerInitialMetadata>();

View File

@ -47,10 +47,10 @@ class HttpClientFilter : public ImplementChannelFilter<HttpClientFilter> {
void OnClientInitialMetadata(ClientMetadata& md, HttpClientFilter* filter); void OnClientInitialMetadata(ClientMetadata& md, HttpClientFilter* filter);
absl::Status OnServerInitialMetadata(ServerMetadata& md); absl::Status OnServerInitialMetadata(ServerMetadata& md);
absl::Status OnServerTrailingMetadata(ServerMetadata& md); absl::Status OnServerTrailingMetadata(ServerMetadata& md);
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
}; };
private: private:

View File

@ -23,10 +23,10 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <optional>
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/security/transport/auth_filters.h" #include "src/core/lib/security/transport/auth_filters.h"
@ -36,16 +36,9 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor ClientAuthorityFilter::Call::OnServerInitialMetadata;
const NoInterceptor ClientAuthorityFilter::Call::OnServerTrailingMetadata;
const NoInterceptor ClientAuthorityFilter::Call::OnClientToServerMessage;
const NoInterceptor ClientAuthorityFilter::Call::OnClientToServerHalfClose;
const NoInterceptor ClientAuthorityFilter::Call::OnServerToClientMessage;
const NoInterceptor ClientAuthorityFilter::Call::OnFinalize;
absl::StatusOr<std::unique_ptr<ClientAuthorityFilter>> absl::StatusOr<std::unique_ptr<ClientAuthorityFilter>>
ClientAuthorityFilter::Create(const ChannelArgs& args, ChannelFilter::Args) { ClientAuthorityFilter::Create(const ChannelArgs& args, ChannelFilter::Args) {
absl::optional<absl::string_view> default_authority = std::optional<absl::string_view> default_authority =
args.GetString(GRPC_ARG_DEFAULT_AUTHORITY); args.GetString(GRPC_ARG_DEFAULT_AUTHORITY);
if (!default_authority.has_value()) { if (!default_authority.has_value()) {
return absl::InvalidArgumentError( return absl::InvalidArgumentError(
@ -80,11 +73,13 @@ void RegisterClientAuthorityFilter(CoreConfiguration::Builder* builder) {
builder->channel_init() builder->channel_init()
->RegisterFilter<ClientAuthorityFilter>(GRPC_CLIENT_SUBCHANNEL) ->RegisterFilter<ClientAuthorityFilter>(GRPC_CLIENT_SUBCHANNEL)
.If(NeedsClientAuthorityFilter) .If(NeedsClientAuthorityFilter)
.Before<ClientAuthFilter>(); .Before<ClientAuthFilter>()
.Before<LegacyClientAuthFilter>();
builder->channel_init() builder->channel_init()
->RegisterFilter<ClientAuthorityFilter>(GRPC_CLIENT_DIRECT_CHANNEL) ->RegisterFilter<ClientAuthorityFilter>(GRPC_CLIENT_DIRECT_CHANNEL)
.If(NeedsClientAuthorityFilter) .If(NeedsClientAuthorityFilter)
.Before<ClientAuthFilter>(); .Before<ClientAuthFilter>()
.Before<LegacyClientAuthFilter>();
} }
} // namespace grpc_core } // namespace grpc_core

View File

@ -50,12 +50,12 @@ class ClientAuthorityFilter final
public: public:
void OnClientInitialMetadata(ClientMetadata& md, void OnClientInitialMetadata(ClientMetadata& md,
ClientAuthorityFilter* filter); ClientAuthorityFilter* filter);
static const NoInterceptor OnServerInitialMetadata; static inline const NoInterceptor OnServerInitialMetadata;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
}; };
private: private:

View File

@ -23,13 +23,13 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <optional>
#include <utility> #include <utility>
#include "absl/log/check.h" #include "absl/log/check.h"
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include "absl/types/optional.h"
#include "src/core/ext/filters/message_size/message_size_filter.h" #include "src/core/ext/filters/message_size/message_size_filter.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/channel_stack.h"
@ -52,13 +52,6 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor ServerCompressionFilter::Call::OnClientToServerHalfClose;
const NoInterceptor ServerCompressionFilter::Call::OnServerTrailingMetadata;
const NoInterceptor ServerCompressionFilter::Call::OnFinalize;
const NoInterceptor ClientCompressionFilter::Call::OnClientToServerHalfClose;
const NoInterceptor ClientCompressionFilter::Call::OnServerTrailingMetadata;
const NoInterceptor ClientCompressionFilter::Call::OnFinalize;
const grpc_channel_filter ClientCompressionFilter::kFilter = const grpc_channel_filter ClientCompressionFilter::kFilter =
MakePromiseBasedFilter<ClientCompressionFilter, FilterEndpoint::kClient, MakePromiseBasedFilter<ClientCompressionFilter, FilterEndpoint::kClient,
kFilterExaminesServerInitialMetadata | kFilterExaminesServerInitialMetadata |
@ -108,13 +101,13 @@ ChannelCompression::ChannelCompression(const ChannelArgs& args)
} }
MessageHandle ChannelCompression::CompressMessage( MessageHandle ChannelCompression::CompressMessage(
MessageHandle message, grpc_compression_algorithm algorithm) const { MessageHandle message, grpc_compression_algorithm algorithm,
CallTracerInterface* call_tracer) const {
GRPC_TRACE_LOG(compression, INFO) GRPC_TRACE_LOG(compression, INFO)
<< "CompressMessage: len=" << message->payload()->Length() << "CompressMessage: len=" << message->payload()->Length()
<< " alg=" << algorithm << " flags=" << message->flags(); << " alg=" << algorithm << " flags=" << message->flags();
auto* call_tracer = MaybeGetContext<CallTracerInterface>();
if (call_tracer != nullptr) { if (call_tracer != nullptr) {
call_tracer->RecordSendMessage(*message->payload()); call_tracer->RecordSendMessage(*message);
} }
// Check if we're allowed to compress this message // Check if we're allowed to compress this message
// (apps might want to disable compression for certain messages to avoid // (apps might want to disable compression for certain messages to avoid
@ -147,7 +140,7 @@ MessageHandle ChannelCompression::CompressMessage(
tmp.Swap(payload); tmp.Swap(payload);
flags |= GRPC_WRITE_INTERNAL_COMPRESS; flags |= GRPC_WRITE_INTERNAL_COMPRESS;
if (call_tracer != nullptr) { if (call_tracer != nullptr) {
call_tracer->RecordSendCompressedMessage(*message->payload()); call_tracer->RecordSendCompressedMessage(*message);
} }
} else { } else {
if (GRPC_TRACE_FLAG_ENABLED(compression)) { if (GRPC_TRACE_FLAG_ENABLED(compression)) {
@ -162,14 +155,14 @@ MessageHandle ChannelCompression::CompressMessage(
} }
absl::StatusOr<MessageHandle> ChannelCompression::DecompressMessage( absl::StatusOr<MessageHandle> ChannelCompression::DecompressMessage(
bool is_client, MessageHandle message, DecompressArgs args) const { bool is_client, MessageHandle message, DecompressArgs args,
CallTracerInterface* call_tracer) const {
GRPC_TRACE_LOG(compression, INFO) GRPC_TRACE_LOG(compression, INFO)
<< "DecompressMessage: len=" << message->payload()->Length() << "DecompressMessage: len=" << message->payload()->Length()
<< " max=" << args.max_recv_message_length.value_or(-1) << " max=" << args.max_recv_message_length.value_or(-1)
<< " alg=" << args.algorithm; << " alg=" << args.algorithm;
auto* call_tracer = MaybeGetContext<CallTracerInterface>();
if (call_tracer != nullptr) { if (call_tracer != nullptr) {
call_tracer->RecordReceivedMessage(*message->payload()); call_tracer->RecordReceivedMessage(*message);
} }
// Check max message length. // Check max message length.
if (args.max_recv_message_length.has_value() && if (args.max_recv_message_length.has_value() &&
@ -199,7 +192,7 @@ absl::StatusOr<MessageHandle> ChannelCompression::DecompressMessage(
message->mutable_flags() &= ~GRPC_WRITE_INTERNAL_COMPRESS; message->mutable_flags() &= ~GRPC_WRITE_INTERNAL_COMPRESS;
message->mutable_flags() |= GRPC_WRITE_INTERNAL_TEST_ONLY_WAS_COMPRESSED; message->mutable_flags() |= GRPC_WRITE_INTERNAL_TEST_ONLY_WAS_COMPRESSED;
if (call_tracer != nullptr) { if (call_tracer != nullptr) {
call_tracer->RecordReceivedDecompressedMessage(*message->payload()); call_tracer->RecordReceivedDecompressedMessage(*message);
} }
return std::move(message); return std::move(message);
} }
@ -240,14 +233,15 @@ void ClientCompressionFilter::Call::OnClientInitialMetadata(
"ClientCompressionFilter::Call::OnClientInitialMetadata"); "ClientCompressionFilter::Call::OnClientInitialMetadata");
compression_algorithm_ = compression_algorithm_ =
filter->compression_engine_.HandleOutgoingMetadata(md); filter->compression_engine_.HandleOutgoingMetadata(md);
call_tracer_ = MaybeGetContext<CallTracerInterface>();
} }
MessageHandle ClientCompressionFilter::Call::OnClientToServerMessage( MessageHandle ClientCompressionFilter::Call::OnClientToServerMessage(
MessageHandle message, ClientCompressionFilter* filter) { MessageHandle message, ClientCompressionFilter* filter) {
GRPC_LATENT_SEE_INNER_SCOPE( GRPC_LATENT_SEE_INNER_SCOPE(
"ClientCompressionFilter::Call::OnClientToServerMessage"); "ClientCompressionFilter::Call::OnClientToServerMessage");
return filter->compression_engine_.CompressMessage(std::move(message), return filter->compression_engine_.CompressMessage(
compression_algorithm_); std::move(message), compression_algorithm_, call_tracer_);
} }
void ClientCompressionFilter::Call::OnServerInitialMetadata( void ClientCompressionFilter::Call::OnServerInitialMetadata(
@ -263,7 +257,7 @@ ClientCompressionFilter::Call::OnServerToClientMessage(
GRPC_LATENT_SEE_INNER_SCOPE( GRPC_LATENT_SEE_INNER_SCOPE(
"ClientCompressionFilter::Call::OnServerToClientMessage"); "ClientCompressionFilter::Call::OnServerToClientMessage");
return filter->compression_engine_.DecompressMessage( return filter->compression_engine_.DecompressMessage(
/*is_client=*/true, std::move(message), decompress_args_); /*is_client=*/true, std::move(message), decompress_args_, call_tracer_);
} }
void ServerCompressionFilter::Call::OnClientInitialMetadata( void ServerCompressionFilter::Call::OnClientInitialMetadata(
@ -279,7 +273,8 @@ ServerCompressionFilter::Call::OnClientToServerMessage(
GRPC_LATENT_SEE_INNER_SCOPE( GRPC_LATENT_SEE_INNER_SCOPE(
"ServerCompressionFilter::Call::OnClientToServerMessage"); "ServerCompressionFilter::Call::OnClientToServerMessage");
return filter->compression_engine_.DecompressMessage( return filter->compression_engine_.DecompressMessage(
/*is_client=*/false, std::move(message), decompress_args_); /*is_client=*/false, std::move(message), decompress_args_,
MaybeGetContext<CallTracerInterface>());
} }
void ServerCompressionFilter::Call::OnServerInitialMetadata( void ServerCompressionFilter::Call::OnServerInitialMetadata(
@ -294,8 +289,9 @@ MessageHandle ServerCompressionFilter::Call::OnServerToClientMessage(
MessageHandle message, ServerCompressionFilter* filter) { MessageHandle message, ServerCompressionFilter* filter) {
GRPC_LATENT_SEE_INNER_SCOPE( GRPC_LATENT_SEE_INNER_SCOPE(
"ServerCompressionFilter::Call::OnServerToClientMessage"); "ServerCompressionFilter::Call::OnServerToClientMessage");
return filter->compression_engine_.CompressMessage(std::move(message), return filter->compression_engine_.CompressMessage(
compression_algorithm_); std::move(message), compression_algorithm_,
MaybeGetContext<CallTracerInterface>());
} }
} // namespace grpc_core } // namespace grpc_core

View File

@ -24,9 +24,10 @@
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <optional>
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_fwd.h" #include "src/core/lib/channel/channel_fwd.h"
#include "src/core/lib/channel/promise_based_filter.h" #include "src/core/lib/channel/promise_based_filter.h"
@ -65,7 +66,7 @@ class ChannelCompression {
struct DecompressArgs { struct DecompressArgs {
grpc_compression_algorithm algorithm; grpc_compression_algorithm algorithm;
absl::optional<uint32_t> max_recv_message_length; std::optional<uint32_t> max_recv_message_length;
}; };
grpc_compression_algorithm default_compression_algorithm() const { grpc_compression_algorithm default_compression_algorithm() const {
@ -83,15 +84,16 @@ class ChannelCompression {
// Compress one message synchronously. // Compress one message synchronously.
MessageHandle CompressMessage(MessageHandle message, MessageHandle CompressMessage(MessageHandle message,
grpc_compression_algorithm algorithm) const; grpc_compression_algorithm algorithm,
CallTracerInterface* call_tracer) const;
// Decompress one message synchronously. // Decompress one message synchronously.
absl::StatusOr<MessageHandle> DecompressMessage(bool is_client, absl::StatusOr<MessageHandle> DecompressMessage(
MessageHandle message, bool is_client, MessageHandle message, DecompressArgs args,
DecompressArgs args) const; CallTracerInterface* call_tracer) const;
private: private:
// Max receive message length, if set. // Max receive message length, if set.
absl::optional<uint32_t> max_recv_size_; std::optional<uint32_t> max_recv_size_;
size_t message_size_service_config_parser_index_; size_t message_size_service_config_parser_index_;
// The default, channel-level, compression algorithm. // The default, channel-level, compression algorithm.
grpc_compression_algorithm default_compression_algorithm_; grpc_compression_algorithm default_compression_algorithm_;
@ -129,13 +131,16 @@ class ClientCompressionFilter final
absl::StatusOr<MessageHandle> OnServerToClientMessage( absl::StatusOr<MessageHandle> OnServerToClientMessage(
MessageHandle message, ClientCompressionFilter* filter); MessageHandle message, ClientCompressionFilter* filter);
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
private: private:
grpc_compression_algorithm compression_algorithm_; grpc_compression_algorithm compression_algorithm_;
ChannelCompression::DecompressArgs decompress_args_; ChannelCompression::DecompressArgs decompress_args_;
// TODO(yashykt): Remove call_tracer_ after migration to call v3 stack. (See
// https://github.com/grpc/grpc/pull/38729 for more information.)
CallTracerInterface* call_tracer_ = nullptr;
}; };
private: private:
@ -168,9 +173,9 @@ class ServerCompressionFilter final
MessageHandle OnServerToClientMessage(MessageHandle message, MessageHandle OnServerToClientMessage(MessageHandle message,
ServerCompressionFilter* filter); ServerCompressionFilter* filter);
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
private: private:
ChannelCompression::DecompressArgs decompress_args_; ChannelCompression::DecompressArgs decompress_args_;

View File

@ -24,12 +24,12 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <optional>
#include <utility> #include <utility>
#include "absl/base/attributes.h" #include "absl/base/attributes.h"
#include "absl/log/log.h" #include "absl/log/log.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/debug/trace.h" #include "src/core/lib/debug/trace.h"
@ -47,11 +47,6 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor HttpServerFilter::Call::OnClientToServerMessage;
const NoInterceptor HttpServerFilter::Call::OnClientToServerHalfClose;
const NoInterceptor HttpServerFilter::Call::OnServerToClientMessage;
const NoInterceptor HttpServerFilter::Call::OnFinalize;
const grpc_channel_filter HttpServerFilter::kFilter = const grpc_channel_filter HttpServerFilter::kFilter =
MakePromiseBasedFilter<HttpServerFilter, FilterEndpoint::kServer, MakePromiseBasedFilter<HttpServerFilter, FilterEndpoint::kServer,
kFilterExaminesServerInitialMetadata>(); kFilterExaminesServerInitialMetadata>();
@ -87,7 +82,7 @@ ServerMetadataHandle HttpServerFilter::Call::OnClientInitialMetadata(
if (filter->allow_put_requests_) { if (filter->allow_put_requests_) {
break; break;
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case HttpMethodMetadata::kInvalid: case HttpMethodMetadata::kInvalid:
case HttpMethodMetadata::kGet: case HttpMethodMetadata::kGet:
return MalformedRequest("Bad method header"); return MalformedRequest("Bad method header");
@ -122,7 +117,7 @@ ServerMetadataHandle HttpServerFilter::Call::OnClientInitialMetadata(
} }
if (md.get_pointer(HttpAuthorityMetadata()) == nullptr) { if (md.get_pointer(HttpAuthorityMetadata()) == nullptr) {
absl::optional<Slice> host = md.Take(HostMetadata()); std::optional<Slice> host = md.Take(HostMetadata());
if (host.has_value()) { if (host.has_value()) {
md.Set(HttpAuthorityMetadata(), std::move(*host)); md.Set(HttpAuthorityMetadata(), std::move(*host));
} }

View File

@ -50,10 +50,10 @@ class HttpServerFilter : public ImplementChannelFilter<HttpServerFilter> {
HttpServerFilter* filter); HttpServerFilter* filter);
void OnServerInitialMetadata(ServerMetadata& md); void OnServerInitialMetadata(ServerMetadata& md);
void OnServerTrailingMetadata(ServerMetadata& md); void OnServerTrailingMetadata(ServerMetadata& md);
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
}; };
private: private:

View File

@ -45,17 +45,6 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor ClientMessageSizeFilter::Call::OnClientInitialMetadata;
const NoInterceptor ClientMessageSizeFilter::Call::OnServerInitialMetadata;
const NoInterceptor ClientMessageSizeFilter::Call::OnServerTrailingMetadata;
const NoInterceptor ClientMessageSizeFilter::Call::OnClientToServerHalfClose;
const NoInterceptor ClientMessageSizeFilter::Call::OnFinalize;
const NoInterceptor ServerMessageSizeFilter::Call::OnClientInitialMetadata;
const NoInterceptor ServerMessageSizeFilter::Call::OnServerInitialMetadata;
const NoInterceptor ServerMessageSizeFilter::Call::OnServerTrailingMetadata;
const NoInterceptor ServerMessageSizeFilter::Call::OnClientToServerHalfClose;
const NoInterceptor ServerMessageSizeFilter::Call::OnFinalize;
// //
// MessageSizeParsedConfig // MessageSizeParsedConfig
// //
@ -76,21 +65,19 @@ MessageSizeParsedConfig MessageSizeParsedConfig::GetFromChannelArgs(
return limits; return limits;
} }
absl::optional<uint32_t> GetMaxRecvSizeFromChannelArgs( std::optional<uint32_t> GetMaxRecvSizeFromChannelArgs(const ChannelArgs& args) {
const ChannelArgs& args) { if (args.WantMinimalStack()) return std::nullopt;
if (args.WantMinimalStack()) return absl::nullopt;
int size = args.GetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH) int size = args.GetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH)
.value_or(GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH); .value_or(GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH);
if (size < 0) return absl::nullopt; if (size < 0) return std::nullopt;
return static_cast<uint32_t>(size); return static_cast<uint32_t>(size);
} }
absl::optional<uint32_t> GetMaxSendSizeFromChannelArgs( std::optional<uint32_t> GetMaxSendSizeFromChannelArgs(const ChannelArgs& args) {
const ChannelArgs& args) { if (args.WantMinimalStack()) return std::nullopt;
if (args.WantMinimalStack()) return absl::nullopt;
int size = args.GetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH) int size = args.GetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH)
.value_or(GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH); .value_or(GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH);
if (size < 0) return absl::nullopt; if (size < 0) return std::nullopt;
return static_cast<uint32_t>(size); return static_cast<uint32_t>(size);
} }
@ -154,7 +141,7 @@ ServerMessageSizeFilter::Create(const ChannelArgs& args, ChannelFilter::Args) {
namespace { namespace {
ServerMetadataHandle CheckPayload(const Message& msg, ServerMetadataHandle CheckPayload(const Message& msg,
absl::optional<uint32_t> max_length, std::optional<uint32_t> max_length,
bool is_client, bool is_send) { bool is_client, bool is_send) {
if (!max_length.has_value()) return nullptr; if (!max_length.has_value()) return nullptr;
GRPC_TRACE_LOG(call, INFO) GRPC_TRACE_LOG(call, INFO)
@ -162,7 +149,7 @@ ServerMetadataHandle CheckPayload(const Message& msg,
<< (is_send ? "send" : "recv") << " len:" << msg.payload()->Length() << (is_send ? "send" : "recv") << " len:" << msg.payload()->Length()
<< " max:" << *max_length; << " max:" << *max_length;
if (msg.payload()->Length() <= *max_length) return nullptr; if (msg.payload()->Length() <= *max_length) return nullptr;
return ServerMetadataFromStatus( return CancelledServerMetadataFromStatus(
GRPC_STATUS_RESOURCE_EXHAUSTED, GRPC_STATUS_RESOURCE_EXHAUSTED,
absl::StrFormat("%s: %s message larger than max (%u vs. %d)", absl::StrFormat("%s: %s message larger than max (%u vs. %d)",
is_client ? "CLIENT" : "SERVER", is_client ? "CLIENT" : "SERVER",
@ -171,8 +158,9 @@ ServerMetadataHandle CheckPayload(const Message& msg,
} }
} // namespace } // namespace
ClientMessageSizeFilter::Call::Call(ClientMessageSizeFilter* filter) void ClientMessageSizeFilter::Call::OnClientInitialMetadata(
: limits_(filter->parsed_config_) { ClientMetadata&, ClientMessageSizeFilter* filter) {
limits_ = filter->parsed_config_;
// Get max sizes from channel data, then merge in per-method config values. // Get max sizes from channel data, then merge in per-method config values.
// Note: Per-method config is only available on the client, so we // Note: Per-method config is only available on the client, so we
// apply the max request size to the send limit and the max response // apply the max request size to the send limit and the max response
@ -181,8 +169,8 @@ ClientMessageSizeFilter::Call::Call(ClientMessageSizeFilter* filter)
MessageSizeParsedConfig::GetFromCallContext( MessageSizeParsedConfig::GetFromCallContext(
GetContext<Arena>(), filter->service_config_parser_index_); GetContext<Arena>(), filter->service_config_parser_index_);
if (config_from_call_context != nullptr) { if (config_from_call_context != nullptr) {
absl::optional<uint32_t> max_send_size = limits_.max_send_size(); std::optional<uint32_t> max_send_size = limits_.max_send_size();
absl::optional<uint32_t> max_recv_size = limits_.max_recv_size(); std::optional<uint32_t> max_recv_size = limits_.max_recv_size();
if (config_from_call_context->max_send_size().has_value() && if (config_from_call_context->max_send_size().has_value() &&
(!max_send_size.has_value() || (!max_send_size.has_value() ||
*config_from_call_context->max_send_size() < *max_send_size)) { *config_from_call_context->max_send_size() < *max_send_size)) {

View File

@ -22,10 +22,10 @@
#include <stdint.h> #include <stdint.h>
#include <memory> #include <memory>
#include <optional>
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_fwd.h" #include "src/core/lib/channel/channel_fwd.h"
@ -42,13 +42,13 @@ namespace grpc_core {
class MessageSizeParsedConfig : public ServiceConfigParser::ParsedConfig { class MessageSizeParsedConfig : public ServiceConfigParser::ParsedConfig {
public: public:
absl::optional<uint32_t> max_send_size() const { return max_send_size_; } std::optional<uint32_t> max_send_size() const { return max_send_size_; }
absl::optional<uint32_t> max_recv_size() const { return max_recv_size_; } std::optional<uint32_t> max_recv_size() const { return max_recv_size_; }
MessageSizeParsedConfig() = default; MessageSizeParsedConfig() = default;
MessageSizeParsedConfig(absl::optional<uint32_t> max_send_size, MessageSizeParsedConfig(std::optional<uint32_t> max_send_size,
absl::optional<uint32_t> max_recv_size) std::optional<uint32_t> max_recv_size)
: max_send_size_(max_send_size), max_recv_size_(max_recv_size) {} : max_send_size_(max_send_size), max_recv_size_(max_recv_size) {}
static const MessageSizeParsedConfig* GetFromCallContext( static const MessageSizeParsedConfig* GetFromCallContext(
@ -59,8 +59,8 @@ class MessageSizeParsedConfig : public ServiceConfigParser::ParsedConfig {
static const JsonLoaderInterface* JsonLoader(const JsonArgs&); static const JsonLoaderInterface* JsonLoader(const JsonArgs&);
private: private:
absl::optional<uint32_t> max_send_size_; std::optional<uint32_t> max_send_size_;
absl::optional<uint32_t> max_recv_size_; std::optional<uint32_t> max_recv_size_;
}; };
class MessageSizeParser : public ServiceConfigParser::Parser { class MessageSizeParser : public ServiceConfigParser::Parser {
@ -79,8 +79,8 @@ class MessageSizeParser : public ServiceConfigParser::Parser {
static absl::string_view parser_name() { return "message_size"; } static absl::string_view parser_name() { return "message_size"; }
}; };
absl::optional<uint32_t> GetMaxRecvSizeFromChannelArgs(const ChannelArgs& args); std::optional<uint32_t> GetMaxRecvSizeFromChannelArgs(const ChannelArgs& args);
absl::optional<uint32_t> GetMaxSendSizeFromChannelArgs(const ChannelArgs& args); std::optional<uint32_t> GetMaxSendSizeFromChannelArgs(const ChannelArgs& args);
class ServerMessageSizeFilter final class ServerMessageSizeFilter final
: public ImplementChannelFilter<ServerMessageSizeFilter> { : public ImplementChannelFilter<ServerMessageSizeFilter> {
@ -97,13 +97,13 @@ class ServerMessageSizeFilter final
class Call { class Call {
public: public:
static const NoInterceptor OnClientInitialMetadata; static inline const NoInterceptor OnClientInitialMetadata;
static const NoInterceptor OnServerInitialMetadata; static inline const NoInterceptor OnServerInitialMetadata;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
ServerMetadataHandle OnClientToServerMessage( ServerMetadataHandle OnClientToServerMessage(
const Message& message, ServerMessageSizeFilter* filter); const Message& message, ServerMessageSizeFilter* filter);
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
ServerMetadataHandle OnServerToClientMessage( ServerMetadataHandle OnServerToClientMessage(
const Message& message, ServerMessageSizeFilter* filter); const Message& message, ServerMessageSizeFilter* filter);
}; };
@ -127,14 +127,13 @@ class ClientMessageSizeFilter final
class Call { class Call {
public: public:
explicit Call(ClientMessageSizeFilter* filter); void OnClientInitialMetadata(ClientMetadata&,
ClientMessageSizeFilter* filter);
static const NoInterceptor OnClientInitialMetadata; static inline const NoInterceptor OnServerInitialMetadata;
static const NoInterceptor OnServerInitialMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnFinalize;
static const NoInterceptor OnFinalize;
ServerMetadataHandle OnClientToServerMessage(const Message& message); ServerMetadataHandle OnClientToServerMessage(const Message& message);
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
ServerMetadataHandle OnServerToClientMessage(const Message& message); ServerMetadataHandle OnServerToClientMessage(const Message& message);
private: private:

View File

@ -41,13 +41,6 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor RbacFilter::Call::OnServerInitialMetadata;
const NoInterceptor RbacFilter::Call::OnServerTrailingMetadata;
const NoInterceptor RbacFilter::Call::OnClientToServerMessage;
const NoInterceptor RbacFilter::Call::OnClientToServerHalfClose;
const NoInterceptor RbacFilter::Call::OnServerToClientMessage;
const NoInterceptor RbacFilter::Call::OnFinalize;
absl::Status RbacFilter::Call::OnClientInitialMetadata(ClientMetadata& md, absl::Status RbacFilter::Call::OnClientInitialMetadata(ClientMetadata& md,
RbacFilter* filter) { RbacFilter* filter) {
GRPC_LATENT_SEE_INNER_SCOPE("RbacFilter::Call::OnClientInitialMetadata"); GRPC_LATENT_SEE_INNER_SCOPE("RbacFilter::Call::OnClientInitialMetadata");

View File

@ -52,12 +52,12 @@ class RbacFilter : public ImplementChannelFilter<RbacFilter> {
public: public:
absl::Status OnClientInitialMetadata(ClientMetadata& md, absl::Status OnClientInitialMetadata(ClientMetadata& md,
RbacFilter* filter); RbacFilter* filter);
static const NoInterceptor OnServerInitialMetadata; static inline const NoInterceptor OnServerInitialMetadata;
static const NoInterceptor OnServerTrailingMetadata; static inline const NoInterceptor OnServerTrailingMetadata;
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
}; };
private: private:

View File

@ -22,12 +22,12 @@
#include <cstdint> #include <cstdint>
#include <map> #include <map>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/security/authorization/audit_logging.h" #include "src/core/lib/security/authorization/audit_logging.h"
#include "src/core/util/json/json_args.h" #include "src/core/util/json/json_args.h"
@ -152,7 +152,7 @@ struct RbacConfig {
}; };
struct Authenticated { struct Authenticated {
absl::optional<StringMatch> principal_name; std::optional<StringMatch> principal_name;
static const JsonLoaderInterface* JsonLoader(const JsonArgs&); static const JsonLoaderInterface* JsonLoader(const JsonArgs&);
}; };
@ -218,7 +218,7 @@ struct RbacConfig {
void JsonPostLoad(const Json&, const JsonArgs&, ValidationErrors* errors); void JsonPostLoad(const Json&, const JsonArgs&, ValidationErrors* errors);
}; };
absl::optional<Rules> rules; std::optional<Rules> rules;
Rbac TakeAsRbac(); Rbac TakeAsRbac();
static const JsonLoaderInterface* JsonLoader(const JsonArgs&); static const JsonLoaderInterface* JsonLoader(const JsonArgs&);

View File

@ -22,6 +22,7 @@
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -34,7 +35,6 @@
#include "absl/strings/str_split.h" #include "absl/strings/str_split.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/strings/strip.h" #include "absl/strings/strip.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/ext/filters/stateful_session/stateful_session_service_config_parser.h" #include "src/core/ext/filters/stateful_session/stateful_session_service_config_parser.h"
#include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/channel_stack.h"
@ -54,11 +54,6 @@
namespace grpc_core { namespace grpc_core {
const NoInterceptor StatefulSessionFilter::Call::OnClientToServerMessage;
const NoInterceptor StatefulSessionFilter::Call::OnClientToServerHalfClose;
const NoInterceptor StatefulSessionFilter::Call::OnServerToClientMessage;
const NoInterceptor StatefulSessionFilter::Call::OnFinalize;
UniqueTypeName XdsOverrideHostAttribute::TypeName() { UniqueTypeName XdsOverrideHostAttribute::TypeName() {
static UniqueTypeName::Factory kFactory("xds_override_host"); static UniqueTypeName::Factory kFactory("xds_override_host");
return kFactory.Create(); return kFactory.Create();

View File

@ -85,10 +85,10 @@ class StatefulSessionFilter
StatefulSessionFilter* filter); StatefulSessionFilter* filter);
void OnServerInitialMetadata(ServerMetadata& md); void OnServerInitialMetadata(ServerMetadata& md);
void OnServerTrailingMetadata(ServerMetadata& md); void OnServerTrailingMetadata(ServerMetadata& md);
static const NoInterceptor OnClientToServerMessage; static inline const NoInterceptor OnClientToServerMessage;
static const NoInterceptor OnClientToServerHalfClose; static inline const NoInterceptor OnClientToServerHalfClose;
static const NoInterceptor OnServerToClientMessage; static inline const NoInterceptor OnServerToClientMessage;
static const NoInterceptor OnFinalize; static inline const NoInterceptor OnFinalize;
private: private:
const StatefulSessionMethodParsedConfig::CookieConfig* cookie_config_; const StatefulSessionMethodParsedConfig::CookieConfig* cookie_config_;

View File

@ -18,9 +18,9 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <optional>
#include <vector> #include <vector>
#include "absl/types/optional.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
namespace grpc_core { namespace grpc_core {

View File

@ -21,11 +21,11 @@
#include <stddef.h> #include <stddef.h>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/service_config/service_config_parser.h" #include "src/core/service_config/service_config_parser.h"
@ -45,7 +45,7 @@ class StatefulSessionMethodParsedConfig
: public ServiceConfigParser::ParsedConfig { : public ServiceConfigParser::ParsedConfig {
public: public:
struct CookieConfig { struct CookieConfig {
absl::optional<std::string> name; // Will be unset if disabled. std::optional<std::string> name; // Will be unset if disabled.
std::string path; std::string path;
Duration ttl; Duration ttl;

View File

@ -157,7 +157,6 @@ void Chttp2Connector::OnHandshakeDone(absl::StatusOr<HandshakerArgs*> result) {
timer_handle_ = event_engine_->RunAfter( timer_handle_ = event_engine_->RunAfter(
args_.deadline - Timestamp::Now(), args_.deadline - Timestamp::Now(),
[self = RefAsSubclass<Chttp2Connector>()]() mutable { [self = RefAsSubclass<Chttp2Connector>()]() mutable {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
self->OnTimeout(); self->OnTimeout();
// Ensure the Chttp2Connector is deleted under an ExecCtx. // Ensure the Chttp2Connector is deleted under an ExecCtx.
@ -256,7 +255,7 @@ class Chttp2SecureClientChannelFactory : public ClientChannelFactory {
"security connector already present in channel args."); "security connector already present in channel args.");
} }
// Find the authority to use in the security connector. // Find the authority to use in the security connector.
absl::optional<std::string> authority = std::optional<std::string> authority =
args.GetOwnedString(GRPC_ARG_DEFAULT_AUTHORITY); args.GetOwnedString(GRPC_ARG_DEFAULT_AUTHORITY);
if (!authority.has_value()) { if (!authority.has_value()) {
return absl::InternalError("authority not present in channel args"); return absl::InternalError("authority not present in channel args");

View File

@ -22,8 +22,9 @@
#include <grpc/event_engine/event_engine.h> #include <grpc/event_engine/event_engine.h>
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <optional>
#include "absl/base/thread_annotations.h" #include "absl/base/thread_annotations.h"
#include "absl/types/optional.h"
#include "src/core/client_channel/connector.h" #include "src/core/client_channel/connector.h"
#include "src/core/handshaker/handshaker.h" #include "src/core/handshaker/handshaker.h"
#include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/closure.h"
@ -61,13 +62,13 @@ class Chttp2Connector : public SubchannelConnector {
grpc_closure* notify_ = nullptr; grpc_closure* notify_ = nullptr;
bool shutdown_ = false; bool shutdown_ = false;
grpc_closure on_receive_settings_; grpc_closure on_receive_settings_;
absl::optional<grpc_event_engine::experimental::EventEngine::TaskHandle> std::optional<grpc_event_engine::experimental::EventEngine::TaskHandle>
timer_handle_ ABSL_GUARDED_BY(mu_); timer_handle_ ABSL_GUARDED_BY(mu_);
// A raw pointer will suffice since args_ holds a copy of the ChannelArgs // A raw pointer will suffice since args_ holds a copy of the ChannelArgs
// which holds an std::shared_ptr of the EventEngine. // which holds an std::shared_ptr of the EventEngine.
grpc_event_engine::experimental::EventEngine* event_engine_ grpc_event_engine::experimental::EventEngine* event_engine_
ABSL_GUARDED_BY(mu_); ABSL_GUARDED_BY(mu_);
absl::optional<grpc_error_handle> notify_error_; std::optional<grpc_error_handle> notify_error_;
RefCountedPtr<HandshakeManager> handshake_mgr_; RefCountedPtr<HandshakeManager> handshake_mgr_;
}; };

View File

@ -32,6 +32,7 @@
#include <algorithm> #include <algorithm>
#include <map> #include <map>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -45,7 +46,6 @@
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/strings/strip.h" #include "absl/strings/strip.h"
#include "absl/types/optional.h"
#include "src/core/channelz/channelz.h" #include "src/core/channelz/channelz.h"
#include "src/core/config/core_configuration.h" #include "src/core/config/core_configuration.h"
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
@ -82,6 +82,7 @@
#include "src/core/lib/transport/transport.h" #include "src/core/lib/transport/transport.h"
#include "src/core/server/server.h" #include "src/core/server/server.h"
#include "src/core/util/debug_location.h" #include "src/core/util/debug_location.h"
#include "src/core/util/match.h"
#include "src/core/util/orphanable.h" #include "src/core/util/orphanable.h"
#include "src/core/util/ref_counted_ptr.h" #include "src/core/util/ref_counted_ptr.h"
#include "src/core/util/status_helper.h" #include "src/core/util/status_helper.h"
@ -107,24 +108,26 @@ const char kUnixUriPrefix[] = "unix:";
const char kUnixAbstractUriPrefix[] = "unix-abstract:"; const char kUnixAbstractUriPrefix[] = "unix-abstract:";
const char kVSockUriPrefix[] = "vsock:"; const char kVSockUriPrefix[] = "vsock:";
struct AcceptorDeleter { namespace {
void operator()(grpc_tcp_server_acceptor* acceptor) const { Timestamp GetConnectionDeadline(const ChannelArgs& args) {
gpr_free(acceptor); return Timestamp::Now() +
std::max(
Duration::Milliseconds(1),
args.GetDurationFromIntMillis(GRPC_ARG_SERVER_HANDSHAKE_TIMEOUT_MS)
.value_or(Duration::Minutes(2)));
} }
}; } // namespace
using AcceptorPtr = std::unique_ptr<grpc_tcp_server_acceptor, AcceptorDeleter>; using AcceptorPtr = std::unique_ptr<grpc_tcp_server_acceptor, AcceptorDeleter>;
class Chttp2ServerListener : public Server::ListenerInterface { class Chttp2ServerListener : public Server::ListenerInterface {
public: public:
static grpc_error_handle Create(Server* server, static grpc_error_handle Create(Server* server,
const EventEngine::ResolvedAddress& addr, const EventEngine::ResolvedAddress& addr,
const ChannelArgs& args, const ChannelArgs& args, int* port_num);
Chttp2ServerArgsModifier args_modifier,
int* port_num);
static grpc_error_handle CreateWithAcceptor( static grpc_error_handle CreateWithAcceptor(Server* server, const char* name,
Server* server, const char* name, const ChannelArgs& args, const ChannelArgs& args);
Chttp2ServerArgsModifier args_modifier);
static Chttp2ServerListener* CreateForPassiveListener( static Chttp2ServerListener* CreateForPassiveListener(
Server* server, const ChannelArgs& args, Server* server, const ChannelArgs& args,
@ -132,14 +135,12 @@ class Chttp2ServerListener : public Server::ListenerInterface {
// Do not instantiate directly. Use one of the factory methods above. // Do not instantiate directly. Use one of the factory methods above.
Chttp2ServerListener(Server* server, const ChannelArgs& args, Chttp2ServerListener(Server* server, const ChannelArgs& args,
Chttp2ServerArgsModifier args_modifier, ServerConfigFetcher* config_fetcher,
grpc_server_config_fetcher* config_fetcher,
std::shared_ptr<experimental::PassiveListenerImpl> std::shared_ptr<experimental::PassiveListenerImpl>
passive_listener = nullptr); passive_listener = nullptr);
~Chttp2ServerListener() override; ~Chttp2ServerListener() override;
void Start(Server* server, void Start() override;
const std::vector<grpc_pollset*>* pollsets) override;
void AcceptConnectedEndpoint(std::unique_ptr<EventEngine::Endpoint> endpoint); void AcceptConnectedEndpoint(std::unique_ptr<EventEngine::Endpoint> endpoint);
@ -147,6 +148,15 @@ class Chttp2ServerListener : public Server::ListenerInterface {
return channelz_listen_socket_.get(); return channelz_listen_socket_.get();
} }
void SetServerListenerState(
RefCountedPtr<Server::ListenerState> /*listener_state*/) override {}
const grpc_resolved_address* resolved_address() const override {
// Should only be invoked with experiment server_listener
Crash("Illegal");
return nullptr;
}
void SetOnDestroyDone(grpc_closure* on_destroy_done) override; void SetOnDestroyDone(grpc_closure* on_destroy_done) override;
void Orphan() override; void Orphan() override;
@ -154,14 +164,13 @@ class Chttp2ServerListener : public Server::ListenerInterface {
private: private:
friend class experimental::PassiveListenerImpl; friend class experimental::PassiveListenerImpl;
class ConfigFetcherWatcher class ConfigFetcherWatcher : public ServerConfigFetcher::WatcherInterface {
: public grpc_server_config_fetcher::WatcherInterface {
public: public:
explicit ConfigFetcherWatcher(RefCountedPtr<Chttp2ServerListener> listener) explicit ConfigFetcherWatcher(RefCountedPtr<Chttp2ServerListener> listener)
: listener_(std::move(listener)) {} : listener_(std::move(listener)) {}
void UpdateConnectionManager( void UpdateConnectionManager(
RefCountedPtr<grpc_server_config_fetcher::ConnectionManager> RefCountedPtr<ServerConfigFetcher::ConnectionManager>
connection_manager) override; connection_manager) override;
void StopServing() override; void StopServing() override;
@ -203,7 +212,7 @@ class Chttp2ServerListener : public Server::ListenerInterface {
ABSL_GUARDED_BY(&ActiveConnection::mu_); ABSL_GUARDED_BY(&ActiveConnection::mu_);
// State for enforcing handshake timeout on receiving HTTP/2 settings. // State for enforcing handshake timeout on receiving HTTP/2 settings.
Timestamp const deadline_; Timestamp const deadline_;
absl::optional<EventEngine::TaskHandle> timer_handle_ std::optional<EventEngine::TaskHandle> timer_handle_
ABSL_GUARDED_BY(&ActiveConnection::mu_); ABSL_GUARDED_BY(&ActiveConnection::mu_);
grpc_closure on_receive_settings_ ABSL_GUARDED_BY(&ActiveConnection::mu_); grpc_closure on_receive_settings_ ABSL_GUARDED_BY(&ActiveConnection::mu_);
grpc_pollset_set* const interested_parties_; grpc_pollset_set* const interested_parties_;
@ -241,7 +250,7 @@ class Chttp2ServerListener : public Server::ListenerInterface {
RefCountedPtr<grpc_chttp2_transport> transport_ ABSL_GUARDED_BY(&mu_) = RefCountedPtr<grpc_chttp2_transport> transport_ ABSL_GUARDED_BY(&mu_) =
nullptr; nullptr;
grpc_closure on_close_; grpc_closure on_close_;
absl::optional<EventEngine::TaskHandle> drain_grace_timer_handle_ std::optional<EventEngine::TaskHandle> drain_grace_timer_handle_
ABSL_GUARDED_BY(&mu_); ABSL_GUARDED_BY(&mu_);
// Use a raw pointer since this event_engine_ is grabbed from the // Use a raw pointer since this event_engine_ is grabbed from the
// ChannelArgs of the listener_. // ChannelArgs of the listener_.
@ -267,12 +276,11 @@ class Chttp2ServerListener : public Server::ListenerInterface {
Server* const server_ = nullptr; Server* const server_ = nullptr;
grpc_tcp_server* tcp_server_ = nullptr; grpc_tcp_server* tcp_server_ = nullptr;
grpc_resolved_address resolved_address_; grpc_resolved_address resolved_address_;
Chttp2ServerArgsModifier const args_modifier_;
ConfigFetcherWatcher* config_fetcher_watcher_ = nullptr; ConfigFetcherWatcher* config_fetcher_watcher_ = nullptr;
ChannelArgs args_; ChannelArgs args_;
Mutex mu_; Mutex mu_;
RefCountedPtr<grpc_server_config_fetcher::ConnectionManager> RefCountedPtr<ServerConfigFetcher::ConnectionManager> connection_manager_
connection_manager_ ABSL_GUARDED_BY(mu_); ABSL_GUARDED_BY(mu_);
// Signals whether grpc_tcp_server_start() has been called. // Signals whether grpc_tcp_server_start() has been called.
bool started_ ABSL_GUARDED_BY(mu_) = false; bool started_ ABSL_GUARDED_BY(mu_) = false;
// Signals whether grpc_tcp_server_start() has completed. // Signals whether grpc_tcp_server_start() has completed.
@ -288,8 +296,8 @@ class Chttp2ServerListener : public Server::ListenerInterface {
RefCountedPtr<channelz::ListenSocketNode> channelz_listen_socket_; RefCountedPtr<channelz::ListenSocketNode> channelz_listen_socket_;
MemoryQuotaRefPtr memory_quota_; MemoryQuotaRefPtr memory_quota_;
ConnectionQuotaRefPtr connection_quota_; ConnectionQuotaRefPtr connection_quota_;
grpc_server_config_fetcher* config_fetcher_ = nullptr; ServerConfigFetcher* config_fetcher_ = nullptr;
// TODO(yashykt): consider using absl::variant<> to minimize memory usage for // TODO(yashykt): consider using std::variant<> to minimize memory usage for
// disjoint cases where different fields are used. // disjoint cases where different fields are used.
std::shared_ptr<experimental::PassiveListenerImpl> passive_listener_; std::shared_ptr<experimental::PassiveListenerImpl> passive_listener_;
}; };
@ -299,9 +307,8 @@ class Chttp2ServerListener : public Server::ListenerInterface {
// //
void Chttp2ServerListener::ConfigFetcherWatcher::UpdateConnectionManager( void Chttp2ServerListener::ConfigFetcherWatcher::UpdateConnectionManager(
RefCountedPtr<grpc_server_config_fetcher::ConnectionManager> RefCountedPtr<ServerConfigFetcher::ConnectionManager> connection_manager) {
connection_manager) { RefCountedPtr<ServerConfigFetcher::ConnectionManager>
RefCountedPtr<grpc_server_config_fetcher::ConnectionManager>
connection_manager_to_destroy; connection_manager_to_destroy;
class GracefulShutdownExistingConnections { class GracefulShutdownExistingConnections {
public: public:
@ -369,14 +376,6 @@ void Chttp2ServerListener::ConfigFetcherWatcher::StopServing() {
// Chttp2ServerListener::ActiveConnection::HandshakingState // Chttp2ServerListener::ActiveConnection::HandshakingState
// //
Timestamp GetConnectionDeadline(const ChannelArgs& args) {
return Timestamp::Now() +
std::max(
Duration::Milliseconds(1),
args.GetDurationFromIntMillis(GRPC_ARG_SERVER_HANDSHAKE_TIMEOUT_MS)
.value_or(Duration::Seconds(120)));
}
Chttp2ServerListener::ActiveConnection::HandshakingState::HandshakingState( Chttp2ServerListener::ActiveConnection::HandshakingState::HandshakingState(
RefCountedPtr<ActiveConnection> connection_ref, RefCountedPtr<ActiveConnection> connection_ref,
grpc_pollset* accepting_pollset, AcceptorPtr acceptor, grpc_pollset* accepting_pollset, AcceptorPtr acceptor,
@ -531,7 +530,6 @@ void Chttp2ServerListener::ActiveConnection::HandshakingState::OnHandshakeDone(
&on_receive_settings_, nullptr, on_close); &on_receive_settings_, nullptr, on_close);
timer_handle_ = connection_->event_engine_->RunAfter( timer_handle_ = connection_->event_engine_->RunAfter(
deadline_ - Timestamp::Now(), [self = Ref()]() mutable { deadline_ - Timestamp::Now(), [self = Ref()]() mutable {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
self->OnTimeout(); self->OnTimeout();
// HandshakingState deletion might require an active ExecCtx. // HandshakingState deletion might require an active ExecCtx.
@ -615,7 +613,6 @@ void Chttp2ServerListener::ActiveConnection::SendGoAway() {
GRPC_ARG_SERVER_CONFIG_CHANGE_DRAIN_GRACE_TIME_MS) GRPC_ARG_SERVER_CONFIG_CHANGE_DRAIN_GRACE_TIME_MS)
.value_or(Duration::Minutes(10))), .value_or(Duration::Minutes(10))),
[self = Ref(DEBUG_LOCATION, "drain_grace_timer")]() mutable { [self = Ref(DEBUG_LOCATION, "drain_grace_timer")]() mutable {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
self->OnDrainGraceTimeExpiry(); self->OnDrainGraceTimeExpiry();
self.reset(DEBUG_LOCATION, "drain_grace_timer"); self.reset(DEBUG_LOCATION, "drain_grace_timer");
@ -708,11 +705,10 @@ void Chttp2ServerListener::ActiveConnection::OnDrainGraceTimeExpiry() {
grpc_error_handle Chttp2ServerListener::Create( grpc_error_handle Chttp2ServerListener::Create(
Server* server, const EventEngine::ResolvedAddress& addr, Server* server, const EventEngine::ResolvedAddress& addr,
const ChannelArgs& args, Chttp2ServerArgsModifier args_modifier, const ChannelArgs& args, int* port_num) {
int* port_num) {
// Create Chttp2ServerListener. // Create Chttp2ServerListener.
OrphanablePtr<Chttp2ServerListener> listener = OrphanablePtr<Chttp2ServerListener> listener =
MakeOrphanable<Chttp2ServerListener>(server, args, args_modifier, MakeOrphanable<Chttp2ServerListener>(server, args,
server->config_fetcher()); server->config_fetcher());
// The tcp_server will be unreffed when the listener is orphaned, which could // 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 // be at the end of this function if the listener was not added to the
@ -752,10 +748,9 @@ grpc_error_handle Chttp2ServerListener::Create(
} }
grpc_error_handle Chttp2ServerListener::CreateWithAcceptor( grpc_error_handle Chttp2ServerListener::CreateWithAcceptor(
Server* server, const char* name, const ChannelArgs& args, Server* server, const char* name, const ChannelArgs& args) {
Chttp2ServerArgsModifier args_modifier) {
auto listener = MakeOrphanable<Chttp2ServerListener>( auto listener = MakeOrphanable<Chttp2ServerListener>(
server, args, args_modifier, server->config_fetcher()); server, args, server->config_fetcher());
grpc_error_handle error = grpc_tcp_server_create( grpc_error_handle error = grpc_tcp_server_create(
&listener->tcp_server_shutdown_complete_, ChannelArgsEndpointConfig(args), &listener->tcp_server_shutdown_complete_, ChannelArgsEndpointConfig(args),
OnAccept, listener.get(), &listener->tcp_server_); OnAccept, listener.get(), &listener->tcp_server_);
@ -772,9 +767,7 @@ Chttp2ServerListener* Chttp2ServerListener::CreateForPassiveListener(
std::shared_ptr<experimental::PassiveListenerImpl> passive_listener) { std::shared_ptr<experimental::PassiveListenerImpl> passive_listener) {
// TODO(hork): figure out how to handle channelz in this case // TODO(hork): figure out how to handle channelz in this case
auto listener = MakeOrphanable<Chttp2ServerListener>( auto listener = MakeOrphanable<Chttp2ServerListener>(
server, args, /*args_modifier=*/ server, args, nullptr, std::move(passive_listener));
[](const ChannelArgs& args, grpc_error_handle*) { return args; }, nullptr,
std::move(passive_listener));
auto listener_ptr = listener.get(); auto listener_ptr = listener.get();
server->AddListener(std::move(listener)); server->AddListener(std::move(listener));
return listener_ptr; return listener_ptr;
@ -782,11 +775,9 @@ Chttp2ServerListener* Chttp2ServerListener::CreateForPassiveListener(
Chttp2ServerListener::Chttp2ServerListener( Chttp2ServerListener::Chttp2ServerListener(
Server* server, const ChannelArgs& args, Server* server, const ChannelArgs& args,
Chttp2ServerArgsModifier args_modifier, ServerConfigFetcher* config_fetcher,
grpc_server_config_fetcher* config_fetcher,
std::shared_ptr<experimental::PassiveListenerImpl> passive_listener) std::shared_ptr<experimental::PassiveListenerImpl> passive_listener)
: server_(server), : server_(server),
args_modifier_(args_modifier),
args_(args), args_(args),
memory_quota_(args.GetObject<ResourceQuota>()->memory_quota()), memory_quota_(args.GetObject<ResourceQuota>()->memory_quota()),
connection_quota_(MakeRefCounted<ConnectionQuota>()), connection_quota_(MakeRefCounted<ConnectionQuota>()),
@ -812,8 +803,7 @@ Chttp2ServerListener::~Chttp2ServerListener() {
} }
// Server callback: start listening on our ports // Server callback: start listening on our ports
void Chttp2ServerListener::Start( void Chttp2ServerListener::Start() {
Server* /*server*/, const std::vector<grpc_pollset*>* /* pollsets */) {
if (config_fetcher_ != nullptr) { if (config_fetcher_ != nullptr) {
auto watcher = std::make_unique<ConfigFetcherWatcher>( auto watcher = std::make_unique<ConfigFetcherWatcher>(
RefAsSubclass<Chttp2ServerListener>()); RefAsSubclass<Chttp2ServerListener>());
@ -848,6 +838,27 @@ void Chttp2ServerListener::AcceptConnectedEndpoint(
/*accepting_pollset=*/nullptr, /*acceptor=*/nullptr); /*accepting_pollset=*/nullptr, /*acceptor=*/nullptr);
} }
namespace {
ChannelArgs ModifyArgsForConnection(const ChannelArgs& args,
grpc_error_handle* error) {
auto* server_credentials = args.GetObject<grpc_server_credentials>();
if (server_credentials == nullptr) {
*error = GRPC_ERROR_CREATE("Could not find server credentials");
return args;
}
auto security_connector = server_credentials->create_security_connector(args);
if (security_connector == nullptr) {
*error = GRPC_ERROR_CREATE(
absl::StrCat("Unable to create secure server with credentials of type ",
server_credentials->type().name()));
return args;
}
return args.SetObject(security_connector);
}
} // namespace
void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp, void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp,
grpc_pollset* accepting_pollset, grpc_pollset* accepting_pollset,
grpc_tcp_server_acceptor* server_acceptor) { grpc_tcp_server_acceptor* server_acceptor) {
@ -855,8 +866,7 @@ void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp,
ChannelArgs args = self->args_; ChannelArgs args = self->args_;
OrphanablePtr<grpc_endpoint> endpoint(tcp); OrphanablePtr<grpc_endpoint> endpoint(tcp);
AcceptorPtr acceptor(server_acceptor); AcceptorPtr acceptor(server_acceptor);
RefCountedPtr<grpc_server_config_fetcher::ConnectionManager> RefCountedPtr<ServerConfigFetcher::ConnectionManager> connection_manager;
connection_manager;
{ {
MutexLock lock(&self->mu_); MutexLock lock(&self->mu_);
connection_manager = self->connection_manager_; connection_manager = self->connection_manager_;
@ -875,7 +885,7 @@ void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp,
return; return;
} }
grpc_error_handle error; grpc_error_handle error;
args = self->args_modifier_(*args_result, &error); args = ModifyArgsForConnection(*args_result, &error);
if (!error.ok()) { if (!error.ok()) {
return; return;
} }
@ -953,19 +963,510 @@ void Chttp2ServerListener::Orphan() {
} }
// //
// Chttp2ServerAddPort() // NewChttp2ServerListener::ActiveConnection::HandshakingState
// //
grpc_error_handle Chttp2ServerAddPort(Server* server, const char* addr, NewChttp2ServerListener::ActiveConnection::HandshakingState::HandshakingState(
RefCountedPtr<ActiveConnection> connection_ref, grpc_tcp_server* tcp_server,
grpc_pollset* accepting_pollset, AcceptorPtr acceptor,
const ChannelArgs& args, OrphanablePtr<grpc_endpoint> endpoint)
: InternallyRefCounted(
GRPC_TRACE_FLAG_ENABLED(chttp2_server_refcount)
? "NewChttp2ServerListener::ActiveConnection::HandshakingState"
: nullptr),
connection_(std::move(connection_ref)),
tcp_server_(tcp_server),
accepting_pollset_(accepting_pollset),
acceptor_(std::move(acceptor)),
interested_parties_(grpc_pollset_set_create()),
deadline_(GetConnectionDeadline(args)),
endpoint_(std::move(endpoint)),
handshake_mgr_(MakeRefCounted<HandshakeManager>()) {
if (accepting_pollset != nullptr) {
grpc_pollset_set_add_pollset(interested_parties_, accepting_pollset_);
}
}
NewChttp2ServerListener::ActiveConnection::HandshakingState::
~HandshakingState() {
if (accepting_pollset_ != nullptr) {
grpc_pollset_set_del_pollset(interested_parties_, accepting_pollset_);
}
grpc_pollset_set_destroy(interested_parties_);
if (tcp_server_ != nullptr) {
grpc_tcp_server_unref(tcp_server_);
}
}
void NewChttp2ServerListener::ActiveConnection::HandshakingState::Orphan() {
connection_->work_serializer_.Run(
[this] {
ShutdownLocked(absl::UnavailableError("Listener stopped serving."));
Unref();
},
DEBUG_LOCATION);
}
void NewChttp2ServerListener::ActiveConnection::HandshakingState::StartLocked(
const ChannelArgs& channel_args) {
if (handshake_mgr_ == nullptr) {
// The connection is already shutting down.
return;
}
CoreConfiguration::Get().handshaker_registry().AddHandshakers(
HANDSHAKER_SERVER, channel_args, interested_parties_,
handshake_mgr_.get());
handshake_mgr_->DoHandshake(
std::move(endpoint_), channel_args, deadline_, acceptor_.get(),
[self = Ref()](absl::StatusOr<HandshakerArgs*> result) mutable {
auto* self_ptr = self.get();
self_ptr->connection_->work_serializer_.Run(
[self = std::move(self), result = std::move(result)]() mutable {
self->OnHandshakeDoneLocked(std::move(result));
},
DEBUG_LOCATION);
});
}
void NewChttp2ServerListener::ActiveConnection::HandshakingState::
ShutdownLocked(absl::Status status) {
if (handshake_mgr_ != nullptr) {
handshake_mgr_->Shutdown(std::move(status));
}
}
void NewChttp2ServerListener::ActiveConnection::HandshakingState::
OnTimeoutLocked() {
if (!timer_handle_.has_value()) {
return;
}
timer_handle_.reset();
auto t = std::get<RefCountedPtr<grpc_chttp2_transport>>(connection_->state_);
t->DisconnectWithError(GRPC_ERROR_CREATE(
"Did not receive HTTP/2 settings before handshake timeout"));
}
void NewChttp2ServerListener::ActiveConnection::HandshakingState::
OnReceiveSettings(void* arg, grpc_error_handle /* error */) {
HandshakingState* self = static_cast<HandshakingState*>(arg);
self->connection_->work_serializer_.Run(
[self] {
if (self->timer_handle_.has_value()) {
self->connection_->listener_state_->event_engine()->Cancel(
*self->timer_handle_);
self->timer_handle_.reset();
}
self->Unref();
},
DEBUG_LOCATION);
}
void NewChttp2ServerListener::ActiveConnection::HandshakingState::
OnHandshakeDoneLocked(absl::StatusOr<HandshakerArgs*> result) {
OrphanablePtr<HandshakingState> handshaking_state_ref;
RefCountedPtr<HandshakeManager> handshake_mgr;
// If the handshaking succeeded but there is no endpoint, then the
// handshaker may have handed off the connection to some external
// code, so we can just clean up here without creating a transport.
if (!connection_->shutdown_ && result.ok() &&
(*result)->endpoint != nullptr) {
RefCountedPtr<Transport> transport =
grpc_create_chttp2_transport((*result)->args,
std::move((*result)->endpoint), false)
->Ref();
grpc_error_handle channel_init_err =
connection_->listener_state_->server()->SetupTransport(
transport.get(), accepting_pollset_, (*result)->args,
grpc_chttp2_transport_get_socket_node(transport.get()));
if (channel_init_err.ok()) {
// Use notify_on_receive_settings callback to enforce the
// handshake deadline.
connection_->state_ =
DownCast<grpc_chttp2_transport*>(transport.get())->Ref();
Ref().release(); // Held by OnReceiveSettings().
GRPC_CLOSURE_INIT(&on_receive_settings_, OnReceiveSettings, this,
grpc_schedule_on_exec_ctx);
grpc_closure* on_close = &connection_->on_close_;
// Refs helds by OnClose()
connection_->Ref().release();
grpc_chttp2_transport_start_reading(
transport.get(), (*result)->read_buffer.c_slice_buffer(),
&on_receive_settings_, nullptr, on_close);
timer_handle_ = connection_->listener_state_->event_engine()->RunAfter(
deadline_ - Timestamp::Now(), [self = Ref()]() mutable {
// HandshakingState deletion might require an active ExecCtx.
ExecCtx exec_ctx;
auto* self_ptr = self.get();
self_ptr->connection_->work_serializer_.Run(
[self = std::move(self)]() { self->OnTimeoutLocked(); },
DEBUG_LOCATION);
});
} else {
// Failed to create channel from transport. Clean up.
LOG(ERROR) << "Failed to create channel: "
<< StatusToString(channel_init_err);
transport->Orphan();
}
}
// Since the handshake manager is done, the connection no longer needs to
// shutdown the handshake when the listener needs to stop serving.
handshake_mgr_.reset();
connection_->listener_state_->OnHandshakeDone(connection_.get());
// Clean up if we don't have a transport
if (!std::holds_alternative<RefCountedPtr<grpc_chttp2_transport>>(
connection_->state_)) {
connection_->listener_state_->connection_quota()->ReleaseConnections(1);
connection_->listener_state_->RemoveLogicalConnection(connection_.get());
}
}
//
// NewChttp2ServerListener::ActiveConnection
//
NewChttp2ServerListener::ActiveConnection::ActiveConnection(
RefCountedPtr<Server::ListenerState> listener_state,
grpc_tcp_server* tcp_server, grpc_pollset* accepting_pollset,
AcceptorPtr acceptor, const ChannelArgs& args, MemoryOwner memory_owner,
OrphanablePtr<grpc_endpoint> endpoint)
: LogicalConnection(GRPC_TRACE_FLAG_ENABLED(chttp2_server_refcount)
? "NewChttp2ServerListener::ActiveConnection"
: nullptr),
listener_state_(std::move(listener_state)),
work_serializer_(
args.GetObjectRef<grpc_event_engine::experimental::EventEngine>()),
state_(memory_owner.MakeOrphanable<HandshakingState>(
RefAsSubclass<ActiveConnection>(), tcp_server, accepting_pollset,
std::move(acceptor), args, std::move(endpoint))) {
GRPC_CLOSURE_INIT(&on_close_, ActiveConnection::OnClose, this,
grpc_schedule_on_exec_ctx);
}
void NewChttp2ServerListener::ActiveConnection::Orphan() {
work_serializer_.Run(
[this]() {
// If ActiveConnection is orphaned before handshake is established,
// shutdown the handshaker. If the server is stopping to serve or
// shutting down and a transport has already been established, GOAWAYs
// should be sent separately.
shutdown_ = true;
if (std::holds_alternative<OrphanablePtr<HandshakingState>>(state_)) {
state_ = OrphanablePtr<HandshakingState>(nullptr);
}
Unref();
},
DEBUG_LOCATION);
}
void NewChttp2ServerListener::ActiveConnection::SendGoAway() {
work_serializer_.Run(
[self = RefAsSubclass<ActiveConnection>()]() mutable {
self->SendGoAwayImplLocked();
},
DEBUG_LOCATION);
}
void NewChttp2ServerListener::ActiveConnection::DisconnectImmediately() {
work_serializer_.Run(
[self = RefAsSubclass<ActiveConnection>()]() mutable {
self->DisconnectImmediatelyImplLocked();
},
DEBUG_LOCATION);
}
void NewChttp2ServerListener::ActiveConnection::Start(const ChannelArgs& args) {
work_serializer_.Run(
[self = RefAsSubclass<ActiveConnection>(), args]() mutable {
// If the Connection is already shutdown at this point, it implies the
// owning NewChttp2ServerListener and all associated
// ActiveConnections have been orphaned.
if (self->shutdown_) return;
std::get<OrphanablePtr<HandshakingState>>(self->state_)
->StartLocked(args);
},
DEBUG_LOCATION);
}
void NewChttp2ServerListener::ActiveConnection::OnClose(
void* arg, grpc_error_handle /* error */) {
ActiveConnection* self = static_cast<ActiveConnection*>(arg);
self->listener_state_->RemoveLogicalConnection(self);
self->listener_state_->connection_quota()->ReleaseConnections(1);
self->Unref();
}
void NewChttp2ServerListener::ActiveConnection::SendGoAwayImplLocked() {
if (!shutdown_) {
shutdown_ = true;
Match(
state_,
[](const OrphanablePtr<HandshakingState>& handshaking_state) {
// Shutdown the handshaker if it's still in progress.
if (handshaking_state != nullptr) {
handshaking_state->ShutdownLocked(
absl::UnavailableError("Connection going away"));
}
},
[](const RefCountedPtr<grpc_chttp2_transport>& transport) {
// Send a GOAWAY if the transport exists
if (transport != nullptr) {
grpc_transport_op* op = grpc_make_transport_op(nullptr);
// Set an HTTP2 error of NO_ERROR to do graceful GOAWAYs.
op->goaway_error = grpc_error_set_int(
GRPC_ERROR_CREATE("Server is stopping to serve requests."),
StatusIntProperty::kHttp2Error, GRPC_HTTP2_NO_ERROR);
transport->PerformOp(op);
}
});
}
}
void NewChttp2ServerListener::ActiveConnection::
DisconnectImmediatelyImplLocked() {
shutdown_ = true;
Match(
state_,
[](const OrphanablePtr<HandshakingState>& handshaking_state) {
// Shutdown the handshaker if it's still in progress.
if (handshaking_state != nullptr) {
handshaking_state->ShutdownLocked(
absl::UnavailableError("Connection to be disconnected"));
}
},
[](const RefCountedPtr<grpc_chttp2_transport>& transport) {
// Disconnect immediately if the transport exists
if (transport != nullptr) {
grpc_transport_op* op = grpc_make_transport_op(nullptr);
op->disconnect_with_error = GRPC_ERROR_CREATE(
"Drain grace time expired. Closing connection immediately.");
transport->PerformOp(op);
}
});
}
//
// NewChttp2ServerListener
//
grpc_error_handle NewChttp2ServerListener::Create(
Server* server, const EventEngine::ResolvedAddress& addr,
const ChannelArgs& args, int* port_num) {
// Create NewChttp2ServerListener.
OrphanablePtr<NewChttp2ServerListener> listener =
MakeOrphanable<NewChttp2ServerListener>(args);
// 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;
// TODO(yijiem): remove this conversion when we remove all
// grpc_resolved_address usages.
grpc_resolved_address iomgr_addr =
grpc_event_engine::experimental::CreateGRPCResolvedAddress(addr);
if (server->config_fetcher() != nullptr) {
// TODO(yashykt): Consider binding so as to be able to return the port
// number.
listener->resolved_address_ = iomgr_addr;
{
MutexLock lock(&listener->mu_);
listener->add_port_on_start_ = true;
}
} else {
error =
grpc_tcp_server_add_port(listener->tcp_server_, &iomgr_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_event_engine::experimental::ResolvedAddressToURI(addr);
if (!string_address.ok()) {
return GRPC_ERROR_CREATE(string_address.status().ToString());
}
listener->channelz_listen_socket_ =
MakeRefCounted<channelz::ListenSocketNode>(
*string_address, absl::StrCat("chttp2 listener ", *string_address));
}
// Register with the server only upon success
server->AddListener(std::move(listener));
return absl::OkStatus();
}
grpc_error_handle NewChttp2ServerListener::CreateWithAcceptor(
Server* server, const char* name, const ChannelArgs& args) {
auto listener = MakeOrphanable<NewChttp2ServerListener>(args);
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;
// TODO(yangg) channelz
TcpServerFdHandler** arg_val = args.GetPointer<TcpServerFdHandler*>(name);
*arg_val = grpc_tcp_server_create_fd_handler(listener->tcp_server_);
server->AddListener(std::move(listener));
return absl::OkStatus();
}
NewChttp2ServerListener* NewChttp2ServerListener::CreateForPassiveListener(
Server* server, const ChannelArgs& args,
std::shared_ptr<experimental::PassiveListenerImpl> passive_listener) {
// TODO(hork): figure out how to handle channelz in this case
auto listener = MakeOrphanable<NewChttp2ServerListener>(
args, std::move(passive_listener));
auto listener_ptr = listener.get();
server->AddListener(std::move(listener));
return listener_ptr;
}
NewChttp2ServerListener::NewChttp2ServerListener(
const ChannelArgs& args, const ChannelArgs& args,
Chttp2ServerArgsModifier args_modifier, std::shared_ptr<experimental::PassiveListenerImpl> passive_listener)
int* port_num) { : ListenerInterface(GRPC_TRACE_FLAG_ENABLED(chttp2_server_refcount)
? "NewChttp2ServerListener"
: nullptr),
args_(args),
passive_listener_(std::move(passive_listener)) {
GRPC_CLOSURE_INIT(&tcp_server_shutdown_complete_, TcpServerShutdownComplete,
this, grpc_schedule_on_exec_ctx);
}
NewChttp2ServerListener::~NewChttp2ServerListener() {
if (passive_listener_ != nullptr) {
passive_listener_->ListenerDestroyed();
}
if (on_destroy_done_ != nullptr) {
ExecCtx::Run(DEBUG_LOCATION, on_destroy_done_, absl::OkStatus());
}
}
void NewChttp2ServerListener::Start() {
bool should_add_port = false;
grpc_tcp_server* tcp_server = nullptr;
{
MutexLock lock(&mu_);
if (!shutdown_) {
should_add_port = std::exchange(add_port_on_start_, false);
// Hold a ref while we start the server
if (tcp_server_ != nullptr) {
grpc_tcp_server_ref(tcp_server_);
tcp_server = tcp_server_;
}
}
}
if (should_add_port) {
int port_temp;
grpc_error_handle error =
grpc_tcp_server_add_port(tcp_server_, resolved_address(), &port_temp);
if (!error.ok()) {
LOG(ERROR) << "Error adding port to server: " << StatusToString(error);
// TODO(yashykt): We wouldn't need to assert here if we bound to the
// port earlier during AddPort.
CHECK(0);
}
}
if (tcp_server != nullptr) {
grpc_tcp_server_start(tcp_server, &listener_state_->server()->pollsets());
// Give up the ref we took earlier
grpc_tcp_server_unref(tcp_server);
}
}
void NewChttp2ServerListener::SetOnDestroyDone(grpc_closure* on_destroy_done) {
MutexLock lock(&mu_);
on_destroy_done_ = on_destroy_done;
}
void NewChttp2ServerListener::AcceptConnectedEndpoint(
std::unique_ptr<EventEngine::Endpoint> endpoint) {
OnAccept(this, grpc_event_engine_endpoint_create(std::move(endpoint)),
/*accepting_pollset=*/nullptr, /*acceptor=*/nullptr);
}
void NewChttp2ServerListener::OnAccept(
void* arg, grpc_endpoint* tcp, grpc_pollset* accepting_pollset,
grpc_tcp_server_acceptor* server_acceptor) {
NewChttp2ServerListener* self = static_cast<NewChttp2ServerListener*>(arg);
OrphanablePtr<grpc_endpoint> endpoint(tcp);
AcceptorPtr acceptor(server_acceptor);
if (!self->listener_state_->connection_quota()->AllowIncomingConnection(
self->listener_state_->memory_quota(),
grpc_endpoint_get_peer(endpoint.get()))) {
return;
}
{
// The ref for the tcp_server need to be taken in the critical region
// after having made sure that the listener has not been Orphaned, so as
// to avoid heap-use-after-free issues where `Ref()` is invoked when the
// listener is already shutdown. Note that the listener holds a ref to the
// tcp_server but this ref is given away when the listener is orphaned
// (shutdown). A connection needs the tcp_server to outlast the handshake
// since the acceptor needs it.
MutexLock lock(&self->mu_);
if (self->shutdown_) {
self->listener_state_->connection_quota()->ReleaseConnections(1);
return;
}
if (self->tcp_server_ != nullptr) {
grpc_tcp_server_ref(self->tcp_server_);
}
}
auto memory_owner =
self->listener_state_->memory_quota()->CreateMemoryOwner();
auto connection = memory_owner.MakeOrphanable<ActiveConnection>(
self->listener_state_, self->tcp_server_, accepting_pollset,
std::move(acceptor), self->args_, std::move(memory_owner),
std::move(endpoint));
RefCountedPtr<ActiveConnection> connection_ref =
connection->RefAsSubclass<ActiveConnection>();
std::optional<ChannelArgs> new_args =
self->listener_state_->AddLogicalConnection(std::move(connection),
self->args_, tcp);
if (new_args.has_value()) {
connection_ref->Start(*new_args);
} else {
self->listener_state_->connection_quota()->ReleaseConnections(1);
}
}
void NewChttp2ServerListener::TcpServerShutdownComplete(
void* arg, grpc_error_handle /*error*/) {
NewChttp2ServerListener* self = static_cast<NewChttp2ServerListener*>(arg);
self->channelz_listen_socket_.reset();
self->Unref();
}
// Server callback: destroy the tcp listener (so we don't generate further
// callbacks)
void NewChttp2ServerListener::Orphan() {
grpc_tcp_server* tcp_server;
{
MutexLock lock(&mu_);
shutdown_ = true;
tcp_server = tcp_server_;
}
if (tcp_server != nullptr) {
grpc_tcp_server_shutdown_listeners(tcp_server);
grpc_tcp_server_unref(tcp_server);
} else {
Unref();
}
}
namespace {
grpc_error_handle Chttp2ServerAddPort(Server* server, const char* addr,
const ChannelArgs& args, int* port_num) {
if (addr == nullptr) { if (addr == nullptr) {
return GRPC_ERROR_CREATE("Invalid address: addr cannot be a nullptr."); return GRPC_ERROR_CREATE("Invalid address: addr cannot be a nullptr.");
} }
if (strncmp(addr, "external:", 9) == 0) { if (strncmp(addr, "external:", 9) == 0) {
return Chttp2ServerListener::CreateWithAcceptor(server, addr, args, if (IsServerListenerEnabled()) {
args_modifier); return NewChttp2ServerListener::CreateWithAcceptor(server, addr, args);
} else {
return Chttp2ServerListener::CreateWithAcceptor(server, addr, args);
}
} }
*port_num = -1; *port_num = -1;
absl::StatusOr<std::vector<grpc_resolved_address>> resolved; absl::StatusOr<std::vector<grpc_resolved_address>> resolved;
@ -1029,8 +1530,11 @@ grpc_error_handle Chttp2ServerAddPort(Server* server, const char* addr,
*port_num); *port_num);
} }
int port_temp = -1; int port_temp = -1;
error = Chttp2ServerListener::Create(server, addr, args, args_modifier, if (IsServerListenerEnabled()) {
&port_temp); error = NewChttp2ServerListener::Create(server, addr, args, &port_temp);
} else {
error = Chttp2ServerListener::Create(server, addr, args, &port_temp);
}
if (!error.ok()) { if (!error.ok()) {
error_list.push_back(error); error_list.push_back(error);
} else { } else {
@ -1063,25 +1567,6 @@ grpc_error_handle Chttp2ServerAddPort(Server* server, const char* addr,
return error; return error;
} }
namespace {
ChannelArgs ModifyArgsForConnection(const ChannelArgs& args,
grpc_error_handle* error) {
auto* server_credentials = args.GetObject<grpc_server_credentials>();
if (server_credentials == nullptr) {
*error = GRPC_ERROR_CREATE("Could not find server credentials");
return args;
}
auto security_connector = server_credentials->create_security_connector(args);
if (security_connector == nullptr) {
*error = GRPC_ERROR_CREATE(
absl::StrCat("Unable to create secure server with credentials of type ",
server_credentials->type().name()));
return args;
}
return args.SetObject(security_connector);
}
} // namespace } // namespace
namespace experimental { namespace experimental {
@ -1089,12 +1574,32 @@ namespace experimental {
absl::Status PassiveListenerImpl::AcceptConnectedEndpoint( absl::Status PassiveListenerImpl::AcceptConnectedEndpoint(
std::unique_ptr<EventEngine::Endpoint> endpoint) { std::unique_ptr<EventEngine::Endpoint> endpoint) {
CHECK_NE(server_.get(), nullptr); CHECK_NE(server_.get(), nullptr);
if (IsServerListenerEnabled()) {
RefCountedPtr<NewChttp2ServerListener> new_listener;
{
MutexLock lock(&mu_);
auto* new_listener_ptr =
std::get_if<NewChttp2ServerListener*>(&listener_);
if (new_listener_ptr != nullptr && *new_listener_ptr != nullptr) {
new_listener = (*new_listener_ptr)
->RefIfNonZero()
.TakeAsSubclass<NewChttp2ServerListener>();
}
}
if (new_listener == nullptr) {
return absl::UnavailableError("passive listener already shut down");
}
ExecCtx exec_ctx;
new_listener->AcceptConnectedEndpoint(std::move(endpoint));
} else {
RefCountedPtr<Chttp2ServerListener> listener; RefCountedPtr<Chttp2ServerListener> listener;
{ {
MutexLock lock(&mu_); MutexLock lock(&mu_);
if (listener_ != nullptr) { auto* listener_ptr = std::get_if<Chttp2ServerListener*>(&listener_);
listener = if (listener_ptr != nullptr && *listener_ptr != nullptr) {
listener_->RefIfNonZero().TakeAsSubclass<Chttp2ServerListener>(); listener = (*listener_ptr)
->RefIfNonZero()
.TakeAsSubclass<Chttp2ServerListener>();
} }
} }
if (listener == nullptr) { if (listener == nullptr) {
@ -1102,6 +1607,7 @@ absl::Status PassiveListenerImpl::AcceptConnectedEndpoint(
} }
ExecCtx exec_ctx; ExecCtx exec_ctx;
listener->AcceptConnectedEndpoint(std::move(endpoint)); listener->AcceptConnectedEndpoint(std::move(endpoint));
}
return absl::OkStatus(); return absl::OkStatus();
} }
@ -1123,7 +1629,7 @@ absl::Status PassiveListenerImpl::AcceptConnectedFd(int fd) {
void PassiveListenerImpl::ListenerDestroyed() { void PassiveListenerImpl::ListenerDestroyed() {
MutexLock lock(&mu_); MutexLock lock(&mu_);
listener_ = nullptr; listener_ = static_cast<Chttp2ServerListener*>(nullptr);
} }
} // namespace experimental } // namespace experimental
@ -1169,8 +1675,7 @@ int grpc_server_add_http2_port(grpc_server* server, const char* addr,
args = args.SetObject(creds->Ref()).SetObject(sc); args = args.SetObject(creds->Ref()).SetObject(sc);
} }
// Add server port. // Add server port.
err = grpc_core::Chttp2ServerAddPort( err = grpc_core::Chttp2ServerAddPort(core_server, addr, args, &port_num);
core_server, addr, args, grpc_core::ModifyArgsForConnection, &port_num);
done: done:
sc.reset(DEBUG_LOCATION, "server"); sc.reset(DEBUG_LOCATION, "server");
if (!err.ok()) { if (!err.ok()) {
@ -1250,9 +1755,16 @@ absl::Status grpc_server_add_passive_listener(
auto args = server->channel_args() auto args = server->channel_args()
.SetObject(credentials->Ref()) .SetObject(credentials->Ref())
.SetObject(std::move(sc)); .SetObject(std::move(sc));
if (grpc_core::IsServerListenerEnabled()) {
passive_listener->listener_ =
grpc_core::NewChttp2ServerListener::CreateForPassiveListener(
server, args, passive_listener);
} else {
passive_listener->listener_ = passive_listener->listener_ =
grpc_core::Chttp2ServerListener::CreateForPassiveListener( grpc_core::Chttp2ServerListener::CreateForPassiveListener(
server, args, passive_listener); server, args, passive_listener);
}
passive_listener->server_ = server->Ref(); passive_listener->server_ = server->Ref();
return absl::OkStatus(); return absl::OkStatus();
} }

View File

@ -19,36 +19,212 @@
#ifndef GRPC_SRC_CORE_EXT_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H #ifndef GRPC_SRC_CORE_EXT_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H
#define GRPC_SRC_CORE_EXT_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H #define GRPC_SRC_CORE_EXT_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H
#include <grpc/event_engine/event_engine.h>
#include <grpc/passive_listener.h> #include <grpc/passive_listener.h>
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <functional> #include <functional>
#include "src/core/ext/transport/chttp2/transport/internal.h"
#include "src/core/handshaker/handshaker.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/error.h" #include "src/core/lib/iomgr/error.h"
#include "src/core/server/server.h" #include "src/core/server/server.h"
namespace grpc_core { namespace grpc_core {
// A function to modify channel args for a listening addr:port. Note that this struct AcceptorDeleter {
// is used to create a security connector for listeners when the servers are void operator()(grpc_tcp_server_acceptor* acceptor) const {
// configured with a config fetcher. Not invoked if there is no config fetcher gpr_free(acceptor);
// added to the server. On failure, the error parameter will be set. }
using Chttp2ServerArgsModifier = };
std::function<ChannelArgs(const ChannelArgs&, grpc_error_handle*)>;
/// Adds a port to \a server. Sets \a port_num to the port number.
/// Takes ownership of \a args.
grpc_error_handle Chttp2ServerAddPort(
Server* server, const char* addr, const ChannelArgs& args,
Chttp2ServerArgsModifier connection_args_modifier, int* port_num);
class Chttp2ServerListener; class Chttp2ServerListener;
namespace testing {
class Chttp2ServerListenerTestPeer;
class ActiveConnectionTestPeer;
class HandshakingStateTestPeer;
} // namespace testing
// New ChttpServerListener used if experiment "server_listener" is enabled
class NewChttp2ServerListener : public Server::ListenerInterface {
public:
using AcceptorPtr =
std::unique_ptr<grpc_tcp_server_acceptor, AcceptorDeleter>;
// Keeps state for an individual connection. Lifetime: Internally refcounted
// and owned by Server::ListenerState.
class ActiveConnection : public LogicalConnection {
public:
// State for handshake. Lifetime: Owned by ActiveConnection and lasts while
// the handshake is ongoing.
class HandshakingState : public InternallyRefCounted<HandshakingState> {
public:
HandshakingState(RefCountedPtr<ActiveConnection> connection_ref,
grpc_tcp_server* tcp_server,
grpc_pollset* accepting_pollset, AcceptorPtr acceptor,
const ChannelArgs& args,
OrphanablePtr<grpc_endpoint> endpoint);
~HandshakingState() override;
void Orphan() override;
void StartLocked(const ChannelArgs& args);
void ShutdownLocked(absl::Status status);
private:
friend class grpc_core::testing::HandshakingStateTestPeer;
void OnTimeoutLocked();
static void OnReceiveSettings(void* arg, grpc_error_handle /* error */);
void OnHandshakeDoneLocked(absl::StatusOr<HandshakerArgs*> result);
RefCountedPtr<ActiveConnection> const connection_;
grpc_tcp_server* const tcp_server_;
grpc_pollset* const accepting_pollset_;
const AcceptorPtr acceptor_;
grpc_pollset_set* const interested_parties_;
Timestamp const deadline_;
OrphanablePtr<grpc_endpoint> endpoint_;
// Following fields are protected by WorkSerializer.
RefCountedPtr<HandshakeManager> handshake_mgr_;
// State for enforcing handshake timeout on receiving HTTP/2 settings.
std::optional<grpc_event_engine::experimental::EventEngine::TaskHandle>
timer_handle_;
grpc_closure on_receive_settings_;
};
ActiveConnection(RefCountedPtr<Server::ListenerState> listener_state,
grpc_tcp_server* tcp_server,
grpc_pollset* accepting_pollset, AcceptorPtr acceptor,
const ChannelArgs& args, MemoryOwner memory_owner,
OrphanablePtr<grpc_endpoint> endpoint);
void Start(const ChannelArgs& args);
void SendGoAway() override;
void DisconnectImmediately() override;
void Orphan() override;
// Needed to be able to grab an external weak ref in
// NewChttp2ServerListener::OnAccept()
using InternallyRefCounted<LogicalConnection>::RefAsSubclass;
private:
friend class grpc_core::testing::ActiveConnectionTestPeer;
friend class grpc_core::testing::HandshakingStateTestPeer;
static void OnClose(void* arg, grpc_error_handle error);
void SendGoAwayImplLocked();
void DisconnectImmediatelyImplLocked();
RefCountedPtr<Server::ListenerState> const listener_state_;
WorkSerializer work_serializer_;
// Following fields are protected by WorkSerializer.
// Set by HandshakingState before the handshaking begins and set to a valid
// transport when handshaking is done successfully.
std::variant<OrphanablePtr<HandshakingState>,
RefCountedPtr<grpc_chttp2_transport>>
state_;
grpc_closure on_close_;
bool shutdown_ = false;
};
static grpc_error_handle Create(
Server* server,
const grpc_event_engine::experimental::EventEngine::ResolvedAddress& addr,
const ChannelArgs& args, int* port_num);
static grpc_error_handle CreateWithAcceptor(Server* server, const char* name,
const ChannelArgs& args);
static NewChttp2ServerListener* CreateForPassiveListener(
Server* server, const ChannelArgs& args,
std::shared_ptr<experimental::PassiveListenerImpl> passive_listener);
// Do not instantiate directly. Use one of the factory methods above.
explicit NewChttp2ServerListener(
const ChannelArgs& args,
std::shared_ptr<experimental::PassiveListenerImpl> passive_listener =
nullptr);
~NewChttp2ServerListener() override;
void AcceptConnectedEndpoint(
std::unique_ptr<grpc_event_engine::experimental::EventEngine::Endpoint>
endpoint);
channelz::ListenSocketNode* channelz_listen_socket_node() const override {
return channelz_listen_socket_.get();
}
void SetServerListenerState(
RefCountedPtr<Server::ListenerState> listener_state) override {
listener_state_ = std::move(listener_state);
}
const grpc_resolved_address* resolved_address() const override {
return &resolved_address_;
}
void SetOnDestroyDone(grpc_closure* on_destroy_done) override;
void Orphan() override;
private:
friend class experimental::PassiveListenerImpl;
// To allow access to RefCounted<> like interface.
friend class RefCountedPtr<NewChttp2ServerListener>;
friend class grpc_core::testing::Chttp2ServerListenerTestPeer;
// Should only be called once so as to start the TCP server. This should
// only be called by the config fetcher.
void Start() override;
static void OnAccept(void* arg, grpc_endpoint* tcp,
grpc_pollset* accepting_pollset,
grpc_tcp_server_acceptor* acceptor);
static void TcpServerShutdownComplete(void* arg, grpc_error_handle error);
static void DestroyListener(Server* /*server*/, void* arg,
grpc_closure* destroy_done);
grpc_event_engine::experimental::EventEngine* event_engine() const {
return listener_state_->server()
->channel_args()
.GetObject<grpc_event_engine::experimental::EventEngine>();
}
grpc_tcp_server* tcp_server_ = nullptr;
grpc_resolved_address resolved_address_;
RefCountedPtr<Server::ListenerState> listener_state_;
ChannelArgs args_;
Mutex mu_;
bool add_port_on_start_ ABSL_GUARDED_BY(mu_) = false;
// Signals whether the application has triggered shutdown.
bool shutdown_ ABSL_GUARDED_BY(mu_) = false;
grpc_closure tcp_server_shutdown_complete_ ABSL_GUARDED_BY(mu_);
grpc_closure* on_destroy_done_ ABSL_GUARDED_BY(mu_) = nullptr;
RefCountedPtr<channelz::ListenSocketNode> channelz_listen_socket_;
// TODO(yashykt): consider using std::variant<> to minimize memory usage for
// disjoint cases where different fields are used.
std::shared_ptr<experimental::PassiveListenerImpl> passive_listener_;
};
namespace experimental { namespace experimental {
// An implementation of the public C++ passive listener interface. // An implementation of the public C++ passive listener interface.
// The server builder holds a weak_ptr to one of these objects, and the // The server builder holds a weak_ptr to one of these objects, and the
// application owns the instance. // application owns the instance.
// TODO(yashykt): Move this to C-Core since this should be transport agnostic.
// Refer to https://github.com/grpc/grpc/pull/37601/files#r1803547924 for
// details.
class PassiveListenerImpl final : public PassiveListener { class PassiveListenerImpl final : public PassiveListener {
public: public:
absl::Status AcceptConnectedEndpoint( absl::Status AcceptConnectedEndpoint(
@ -71,7 +247,7 @@ class PassiveListenerImpl final : public PassiveListener {
Mutex mu_; Mutex mu_;
// Data members will be populated when initialized. // Data members will be populated when initialized.
RefCountedPtr<Server> server_; RefCountedPtr<Server> server_;
Chttp2ServerListener* listener_; std::variant<Chttp2ServerListener*, NewChttp2ServerListener*> listener_;
}; };
} // namespace experimental } // namespace experimental

View File

@ -142,7 +142,7 @@ bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx) {
switch (input_tail) { switch (input_tail) {
case 3: case 3:
ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur); ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur);
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case 2: case 2:
ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur); ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
} }

View File

@ -30,7 +30,7 @@ void Chttp2CallTracerWrapper::RecordIncomingBytes(
stream_->stats.incoming.header_bytes += transport_byte_size.header_bytes; stream_->stats.incoming.header_bytes += transport_byte_size.header_bytes;
// Update new API. // Update new API.
if (!IsCallTracerInTransportEnabled()) return; if (!IsCallTracerInTransportEnabled()) return;
auto* call_tracer = stream_->arena->GetContext<CallTracerInterface>(); auto* call_tracer = stream_->CallTracer();
if (call_tracer != nullptr) { if (call_tracer != nullptr) {
call_tracer->RecordIncomingBytes(transport_byte_size); call_tracer->RecordIncomingBytes(transport_byte_size);
} }
@ -44,7 +44,7 @@ void Chttp2CallTracerWrapper::RecordOutgoingBytes(
stream_->stats.outgoing.header_bytes += stream_->stats.outgoing.header_bytes +=
transport_byte_size.header_bytes; // Update new API. transport_byte_size.header_bytes; // Update new API.
if (!IsCallTracerInTransportEnabled()) return; if (!IsCallTracerInTransportEnabled()) return;
auto* call_tracer = stream_->arena->GetContext<CallTracerInterface>(); auto* call_tracer = stream_->CallTracer();
if (call_tracer != nullptr) { if (call_tracer != nullptr) {
call_tracer->RecordOutgoingBytes(transport_byte_size); call_tracer->RecordOutgoingBytes(transport_byte_size);
} }

View File

@ -45,14 +45,14 @@ class Chttp2CallTracerWrapper final : public CallTracerInterface {
grpc_metadata_batch* /*send_initial_metadata*/) override {} grpc_metadata_batch* /*send_initial_metadata*/) override {}
void RecordSendTrailingMetadata( void RecordSendTrailingMetadata(
grpc_metadata_batch* /*send_trailing_metadata*/) override {} grpc_metadata_batch* /*send_trailing_metadata*/) override {}
void RecordSendMessage(const SliceBuffer& /*send_message*/) override {} void RecordSendMessage(const Message& /*send_message*/) override {}
void RecordSendCompressedMessage( void RecordSendCompressedMessage(
const SliceBuffer& /*send_compressed_message*/) override {} const Message& /*send_compressed_message*/) override {}
void RecordReceivedInitialMetadata( void RecordReceivedInitialMetadata(
grpc_metadata_batch* /*recv_initial_metadata*/) override {} grpc_metadata_batch* /*recv_initial_metadata*/) override {}
void RecordReceivedMessage(const SliceBuffer& /*recv_message*/) override {} void RecordReceivedMessage(const Message& /*recv_message*/) override {}
void RecordReceivedDecompressedMessage( void RecordReceivedDecompressedMessage(
const SliceBuffer& /*recv_decompressed_message*/) override {} const Message& /*recv_decompressed_message*/) override {}
void RecordCancel(grpc_error_handle /*cancel_error*/) override {} void RecordCancel(grpc_error_handle /*cancel_error*/) override {}
std::shared_ptr<TcpTracerInterface> StartNewTcpTrace() override { std::shared_ptr<TcpTracerInterface> StartNewTcpTrace() override {
return nullptr; return nullptr;

View File

@ -36,9 +36,11 @@
#include <limits> #include <limits>
#include <memory> #include <memory>
#include <new> #include <new>
#include <optional>
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#include <variant>
#include <vector> #include <vector>
#include "absl/base/attributes.h" #include "absl/base/attributes.h"
@ -53,8 +55,6 @@
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "src/core/config/config_vars.h" #include "src/core/config/config_vars.h"
#include "src/core/ext/transport/chttp2/transport/call_tracer_wrapper.h" #include "src/core/ext/transport/chttp2/transport/call_tracer_wrapper.h"
#include "src/core/ext/transport/chttp2/transport/context_list_entry.h" #include "src/core/ext/transport/chttp2/transport/context_list_entry.h"
@ -224,26 +224,21 @@ static void send_goaway(grpc_chttp2_transport* t, grpc_error_handle error,
namespace { namespace {
using EventEngine = ::grpc_event_engine::experimental::EventEngine;
using TaskHandle = ::grpc_event_engine::experimental::EventEngine::TaskHandle; using TaskHandle = ::grpc_event_engine::experimental::EventEngine::TaskHandle;
grpc_core::CallTracerAnnotationInterface* CallTracerIfSampled( grpc_core::CallTracerAnnotationInterface* ParentCallTracerIfSampled(
grpc_chttp2_stream* s) { grpc_chttp2_stream* s) {
if (!grpc_core::IsTraceRecordCallopsEnabled()) { auto* parent_call_tracer =
return nullptr;
}
auto* call_tracer =
s->arena->GetContext<grpc_core::CallTracerAnnotationInterface>(); s->arena->GetContext<grpc_core::CallTracerAnnotationInterface>();
if (call_tracer == nullptr || !call_tracer->IsSampled()) { if (parent_call_tracer == nullptr || !parent_call_tracer->IsSampled()) {
return nullptr; return nullptr;
} }
return call_tracer; return parent_call_tracer;
} }
std::shared_ptr<grpc_core::TcpTracerInterface> TcpTracerIfSampled( std::shared_ptr<grpc_core::TcpTracerInterface> TcpTracerIfSampled(
grpc_chttp2_stream* s) { grpc_chttp2_stream* s) {
if (!grpc_core::IsTraceRecordCallopsEnabled()) {
return nullptr;
}
auto* call_attempt_tracer = auto* call_attempt_tracer =
s->arena->GetContext<grpc_core::CallTracerInterface>(); s->arena->GetContext<grpc_core::CallTracerInterface>();
if (call_attempt_tracer == nullptr || !call_attempt_tracer->IsSampled()) { if (call_attempt_tracer == nullptr || !call_attempt_tracer->IsSampled()) {
@ -576,7 +571,6 @@ static void init_keepalive_pings_if_enabled_locked(
t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_WAITING; t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_WAITING;
t->keepalive_ping_timer_handle = t->keepalive_ping_timer_handle =
t->event_engine->RunAfter(t->keepalive_time, [t = t->Ref()]() mutable { t->event_engine->RunAfter(t->keepalive_time, [t = t->Ref()]() mutable {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
init_keepalive_ping(std::move(t)); init_keepalive_ping(std::move(t));
}); });
@ -692,6 +686,8 @@ grpc_chttp2_transport::grpc_chttp2_transport(
read_channel_args(this, channel_args, is_client); read_channel_args(this, channel_args, is_client);
next_adjusted_keepalive_timestamp = grpc_core::Timestamp::InfPast();
// Initially allow *UP TO* MAX_CONCURRENT_STREAMS incoming before we start // Initially allow *UP TO* MAX_CONCURRENT_STREAMS incoming before we start
// blanket cancelling them. // blanket cancelling them.
num_incoming_streams_before_settings_ack = num_incoming_streams_before_settings_ack =
@ -1385,16 +1381,16 @@ static void log_metadata(const grpc_metadata_batch* md_batch, uint32_t id,
} }
static void trace_annotations(grpc_chttp2_stream* s) { static void trace_annotations(grpc_chttp2_stream* s) {
if (!grpc_core::IsCallTracerInTransportEnabled()) { if (!grpc_core::IsCallTracerTransportFixEnabled()) {
if (s->call_tracer != nullptr) { if (s->parent_call_tracer != nullptr) {
s->call_tracer->RecordAnnotation( s->parent_call_tracer->RecordAnnotation(
grpc_core::HttpAnnotation(grpc_core::HttpAnnotation::Type::kStart, grpc_core::HttpAnnotation(grpc_core::HttpAnnotation::Type::kStart,
gpr_now(GPR_CLOCK_REALTIME)) gpr_now(GPR_CLOCK_REALTIME))
.Add(s->t->flow_control.stats()) .Add(s->t->flow_control.stats())
.Add(s->flow_control.stats())); .Add(s->flow_control.stats()));
} }
} else if (grpc_core::IsTraceRecordCallopsEnabled()) { } else {
auto* call_tracer = s->arena->GetContext<grpc_core::CallTracerInterface>(); auto* call_tracer = s->CallTracer();
if (call_tracer != nullptr && call_tracer->IsSampled()) { if (call_tracer != nullptr && call_tracer->IsSampled()) {
call_tracer->RecordAnnotation( call_tracer->RecordAnnotation(
grpc_core::HttpAnnotation(grpc_core::HttpAnnotation::Type::kStart, grpc_core::HttpAnnotation(grpc_core::HttpAnnotation::Type::kStart,
@ -1502,18 +1498,6 @@ static void send_message_locked(
absl::OkStatus(), absl::OkStatus(),
"fetching_send_message_finished"); "fetching_send_message_finished");
} else { } else {
// Buffer hint is used to buffer the message in the transport until the
// write buffer size (specified through GRPC_ARG_HTTP2_WRITE_BUFFER_SIZE) is
// reached. This is to batch writes sent down to tcp. However, if the memory
// pressure is high, disable the buffer hint to flush data down to tcp as
// soon as possible to avoid OOM.
if (grpc_core::IsDisableBufferHintOnHighMemoryPressureEnabled() &&
t->memory_owner.GetPressureInfo().pressure_control_value >= 0.8) {
// Disable write buffer hint if memory pressure is high. The value of 0.8
// is chosen to match the threshold used by the tcp endpoint (in
// allocating memory for socket reads).
op_payload->send_message.flags &= ~GRPC_WRITE_BUFFER_HINT;
}
flags = op_payload->send_message.flags; flags = op_payload->send_message.flags;
uint8_t* frame_hdr = grpc_slice_buffer_tiny_add(&s->flow_controlled_buffer, uint8_t* frame_hdr = grpc_slice_buffer_tiny_add(&s->flow_controlled_buffer,
GRPC_HEADER_SIZE_IN_BYTES); GRPC_HEADER_SIZE_IN_BYTES);
@ -1662,8 +1646,15 @@ static void perform_stream_op_locked(void* stream_op,
grpc_chttp2_transport* t = s->t.get(); grpc_chttp2_transport* t = s->t.get();
s->traced = op->is_traced; s->traced = op->is_traced;
if (!grpc_core::IsCallTracerInTransportEnabled()) { if (!grpc_core::IsCallTracerTransportFixEnabled()) {
s->call_tracer = CallTracerIfSampled(s); s->parent_call_tracer = ParentCallTracerIfSampled(s);
}
// TODO(yashykt): Remove call_tracer field after transition to call v3. (See
// https://github.com/grpc/grpc/pull/38729 for more information.) On the
// client, the call attempt tracer will be available for use when the
// send_initial_metadata op arrives.
if (s->t->is_client && op->send_initial_metadata) {
s->call_tracer = s->arena->GetContext<grpc_core::CallTracerInterface>();
} }
s->tcp_tracer = TcpTracerIfSampled(s); s->tcp_tracer = TcpTracerIfSampled(s);
if (GRPC_TRACE_FLAG_ENABLED(http)) { if (GRPC_TRACE_FLAG_ENABLED(http)) {
@ -1922,14 +1913,24 @@ namespace {
// we add a 20 second deadline, after which we send the second goaway. // we add a 20 second deadline, after which we send the second goaway.
class GracefulGoaway : public grpc_core::RefCounted<GracefulGoaway> { class GracefulGoaway : public grpc_core::RefCounted<GracefulGoaway> {
public: public:
static void Start(grpc_chttp2_transport* t) { new GracefulGoaway(t); } static void Start(grpc_chttp2_transport* t, std::string message) {
new GracefulGoaway(t, std::move(message));
}
private: private:
using TaskHandle = ::grpc_event_engine::experimental::EventEngine::TaskHandle; using TaskHandle = ::grpc_event_engine::experimental::EventEngine::TaskHandle;
explicit GracefulGoaway(grpc_chttp2_transport* t) : t_(t->Ref()) { explicit GracefulGoaway(grpc_chttp2_transport* t, std::string message)
: t_(t->Ref()), message_(std::move(message)) {
GRPC_TRACE_LOG(http, INFO) << "transport:" << t_.get() << " "
<< (t_->is_client ? "CLIENT" : "SERVER")
<< " peer:" << t_->peer_string.as_string_view()
<< " Graceful shutdown: Sending initial GOAWAY.";
t->sent_goaway_state = GRPC_CHTTP2_GRACEFUL_GOAWAY; t->sent_goaway_state = GRPC_CHTTP2_GRACEFUL_GOAWAY;
grpc_chttp2_goaway_append((1u << 31) - 1, 0, grpc_empty_slice(), &t->qbuf); // Graceful GOAWAYs require a NO_ERROR error code
grpc_chttp2_goaway_append(
(1u << 31) - 1, 0 /*NO_ERROR*/,
grpc_core::Slice::FromCopiedString(message_).TakeCSlice(), &t->qbuf);
t->keepalive_timeout = t->keepalive_timeout =
std::min(t->keepalive_timeout, grpc_core::Duration::Seconds(20)); std::min(t->keepalive_timeout, grpc_core::Duration::Seconds(20));
t->ping_timeout = t->ping_timeout =
@ -1961,8 +1962,9 @@ class GracefulGoaway : public grpc_core::RefCounted<GracefulGoaway> {
"Sending final GOAWAY with stream_id:" "Sending final GOAWAY with stream_id:"
<< t_->last_new_stream_id; << t_->last_new_stream_id;
t_->sent_goaway_state = GRPC_CHTTP2_FINAL_GOAWAY_SEND_SCHEDULED; t_->sent_goaway_state = GRPC_CHTTP2_FINAL_GOAWAY_SEND_SCHEDULED;
grpc_chttp2_goaway_append(t_->last_new_stream_id, 0, grpc_empty_slice(), grpc_chttp2_goaway_append(
&t_->qbuf); t_->last_new_stream_id, 0 /*NO_ERROR*/,
grpc_core::Slice::FromCopiedString(message_).TakeCSlice(), &t_->qbuf);
grpc_chttp2_initiate_write(t_.get(), grpc_chttp2_initiate_write(t_.get(),
GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT); GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT);
} }
@ -1982,6 +1984,7 @@ class GracefulGoaway : public grpc_core::RefCounted<GracefulGoaway> {
const grpc_core::RefCountedPtr<grpc_chttp2_transport> t_; const grpc_core::RefCountedPtr<grpc_chttp2_transport> t_;
grpc_closure on_ping_ack_; grpc_closure on_ping_ack_;
std::string message_;
}; };
} // namespace } // namespace
@ -1992,11 +1995,10 @@ static void send_goaway(grpc_chttp2_transport* t, grpc_error_handle error,
std::string message; std::string message;
grpc_error_get_status(error, grpc_core::Timestamp::InfFuture(), nullptr, grpc_error_get_status(error, grpc_core::Timestamp::InfFuture(), nullptr,
&message, &http_error, nullptr); &message, &http_error, nullptr);
if (!t->is_client && http_error == GRPC_HTTP2_NO_ERROR && if (!t->is_client && !immediate_disconnect_hint) {
!immediate_disconnect_hint) {
// Do a graceful shutdown. // Do a graceful shutdown.
if (t->sent_goaway_state == GRPC_CHTTP2_NO_GOAWAY_SEND) { if (t->sent_goaway_state == GRPC_CHTTP2_NO_GOAWAY_SEND) {
GracefulGoaway::Start(t); GracefulGoaway::Start(t, std::move(message));
} else { } else {
// Graceful GOAWAY is already in progress. // Graceful GOAWAY is already in progress.
} }
@ -2275,7 +2277,6 @@ void MaybeTarpit(grpc_chttp2_transport* t, bool tarpit, F fn) {
const auto duration = TarpitDuration(t); const auto duration = TarpitDuration(t);
t->event_engine->RunAfter( t->event_engine->RunAfter(
duration, [t = t->Ref(), fn = std::move(fn)]() mutable { duration, [t = t->Ref(), fn = std::move(fn)]() mutable {
ApplicationCallbackExecCtx app_exec_ctx;
ExecCtx exec_ctx; ExecCtx exec_ctx;
t->combiner->Run( t->combiner->Run(
NewClosure([t, fn = std::move(fn)](grpc_error_handle) mutable { NewClosure([t, fn = std::move(fn)](grpc_error_handle) mutable {
@ -2681,7 +2682,7 @@ static void WithUrgency(grpc_chttp2_transport* t,
break; break;
case grpc_core::chttp2::FlowControlAction::Urgency::UPDATE_IMMEDIATELY: case grpc_core::chttp2::FlowControlAction::Urgency::UPDATE_IMMEDIATELY:
grpc_chttp2_initiate_write(t, reason); grpc_chttp2_initiate_write(t, reason);
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case grpc_core::chttp2::FlowControlAction::Urgency::QUEUE_UPDATE: case grpc_core::chttp2::FlowControlAction::Urgency::QUEUE_UPDATE:
action(); action();
break; break;
@ -2766,7 +2767,7 @@ static void read_action_parse_loop_locked(
i < t->read_buffer.count && errors[1] == absl::OkStatus(); i++) { i < t->read_buffer.count && errors[1] == absl::OkStatus(); i++) {
auto r = grpc_chttp2_perform_read(t.get(), t->read_buffer.slices[i], auto r = grpc_chttp2_perform_read(t.get(), t->read_buffer.slices[i],
requests_started); requests_started);
if (auto* partial_read_size = absl::get_if<size_t>(&r)) { if (auto* partial_read_size = std::get_if<size_t>(&r)) {
for (size_t j = 0; j < i; j++) { for (size_t j = 0; j < i; j++) {
grpc_core::CSliceUnref(grpc_slice_buffer_take_first(&t->read_buffer)); grpc_core::CSliceUnref(grpc_slice_buffer_take_first(&t->read_buffer));
} }
@ -2782,7 +2783,7 @@ static void read_action_parse_loop_locked(
// Early return: we queued to retry later. // Early return: we queued to retry later.
return; return;
} else { } else {
errors[1] = std::move(absl::get<absl::Status>(r)); errors[1] = std::move(std::get<absl::Status>(r));
} }
} }
if (errors[1] != absl::OkStatus()) { if (errors[1] != absl::OkStatus()) {
@ -2944,7 +2945,6 @@ static void finish_bdp_ping_locked(
CHECK(t->next_bdp_ping_timer_handle == TaskHandle::kInvalid); CHECK(t->next_bdp_ping_timer_handle == TaskHandle::kInvalid);
t->next_bdp_ping_timer_handle = t->next_bdp_ping_timer_handle =
t->event_engine->RunAfter(next_ping - grpc_core::Timestamp::Now(), [t] { t->event_engine->RunAfter(next_ping - grpc_core::Timestamp::Now(), [t] {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
next_bdp_ping_timer_expired(t.get()); next_bdp_ping_timer_expired(t.get());
}); });
@ -3032,18 +3032,27 @@ static void init_keepalive_ping_locked(
CHECK(t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING); CHECK(t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING);
CHECK(t->keepalive_ping_timer_handle != TaskHandle::kInvalid); CHECK(t->keepalive_ping_timer_handle != TaskHandle::kInvalid);
t->keepalive_ping_timer_handle = TaskHandle::kInvalid; t->keepalive_ping_timer_handle = TaskHandle::kInvalid;
grpc_core::Timestamp now = grpc_core::Timestamp::Now();
grpc_core::Timestamp adjusted_keepalive_timestamp = std::exchange(
t->next_adjusted_keepalive_timestamp, grpc_core::Timestamp::InfPast());
bool delay_callback = grpc_core::IsKeepAlivePingTimerBatchEnabled() &&
adjusted_keepalive_timestamp > now;
if (t->destroying || !t->closed_with_error.ok()) { if (t->destroying || !t->closed_with_error.ok()) {
t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING; t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING;
} else { } else {
if (t->keepalive_permit_without_calls || !t->stream_map.empty()) { if (!delay_callback &&
(t->keepalive_permit_without_calls || !t->stream_map.empty())) {
t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_PINGING; t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_PINGING;
send_keepalive_ping_locked(t); send_keepalive_ping_locked(t);
grpc_chttp2_initiate_write(t.get(), grpc_chttp2_initiate_write(t.get(),
GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING); GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING);
} else { } else {
grpc_core::Duration extend = grpc_core::Duration::Zero();
if (delay_callback) {
extend = adjusted_keepalive_timestamp - now;
}
t->keepalive_ping_timer_handle = t->keepalive_ping_timer_handle =
t->event_engine->RunAfter(t->keepalive_time, [t] { t->event_engine->RunAfter(t->keepalive_time + extend, [t] {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
init_keepalive_ping(t); init_keepalive_ping(t);
}); });
@ -3075,7 +3084,6 @@ static void finish_keepalive_ping_locked(
CHECK(t->keepalive_ping_timer_handle == TaskHandle::kInvalid); CHECK(t->keepalive_ping_timer_handle == TaskHandle::kInvalid);
t->keepalive_ping_timer_handle = t->keepalive_ping_timer_handle =
t->event_engine->RunAfter(t->keepalive_time, [t] { t->event_engine->RunAfter(t->keepalive_time, [t] {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
init_keepalive_ping(t); init_keepalive_ping(t);
}); });
@ -3083,9 +3091,32 @@ static void finish_keepalive_ping_locked(
} }
} }
// Returns true if the timer was successfully extended. The provided callback
// is used only if the timer was not previously scheduled with slack.
static bool ExtendScheduledTimer(grpc_chttp2_transport* t, TaskHandle& handle,
grpc_core::Duration duration,
absl::AnyInvocable<void()> cb) {
if (handle == TaskHandle::kInvalid) {
return false;
}
if (grpc_core::IsKeepAlivePingTimerBatchEnabled()) {
t->next_adjusted_keepalive_timestamp =
grpc_core::Timestamp::Now() + duration;
return true;
}
if (t->event_engine->Cancel(handle)) {
handle = t->event_engine->RunAfter(duration, std::move(cb));
return true;
}
return false;
}
static void maybe_reset_keepalive_ping_timer_locked(grpc_chttp2_transport* t) { static void maybe_reset_keepalive_ping_timer_locked(grpc_chttp2_transport* t) {
if (t->keepalive_ping_timer_handle != TaskHandle::kInvalid && if (ExtendScheduledTimer(t, t->keepalive_ping_timer_handle, t->keepalive_time,
t->event_engine->Cancel(t->keepalive_ping_timer_handle)) { [t = t->Ref()]() mutable {
grpc_core::ExecCtx exec_ctx;
init_keepalive_ping(std::move(t));
})) {
// Cancel succeeds, resets the keepalive ping timer. Note that we don't // Cancel succeeds, resets the keepalive ping timer. Note that we don't
// need to Ref or Unref here since we still hold the Ref. // need to Ref or Unref here since we still hold the Ref.
if (GRPC_TRACE_FLAG_ENABLED(http) || if (GRPC_TRACE_FLAG_ENABLED(http) ||
@ -3093,12 +3124,6 @@ static void maybe_reset_keepalive_ping_timer_locked(grpc_chttp2_transport* t) {
LOG(INFO) << t->peer_string.as_string_view() LOG(INFO) << t->peer_string.as_string_view()
<< ": Keepalive ping cancelled. Resetting timer."; << ": Keepalive ping cancelled. Resetting timer.";
} }
t->keepalive_ping_timer_handle =
t->event_engine->RunAfter(t->keepalive_time, [t = t->Ref()]() mutable {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
init_keepalive_ping(std::move(t));
});
} }
} }
@ -3150,7 +3175,7 @@ static void post_benign_reclaimer(grpc_chttp2_transport* t) {
t->memory_owner.PostReclaimer( t->memory_owner.PostReclaimer(
grpc_core::ReclamationPass::kBenign, grpc_core::ReclamationPass::kBenign,
[t = t->Ref()]( [t = t->Ref()](
absl::optional<grpc_core::ReclamationSweep> sweep) mutable { std::optional<grpc_core::ReclamationSweep> sweep) mutable {
if (sweep.has_value()) { if (sweep.has_value()) {
auto* tp = t.get(); auto* tp = t.get();
tp->active_reclamation = std::move(*sweep); tp->active_reclamation = std::move(*sweep);
@ -3169,7 +3194,7 @@ static void post_destructive_reclaimer(grpc_chttp2_transport* t) {
t->memory_owner.PostReclaimer( t->memory_owner.PostReclaimer(
grpc_core::ReclamationPass::kDestructive, grpc_core::ReclamationPass::kDestructive,
[t = t->Ref()]( [t = t->Ref()](
absl::optional<grpc_core::ReclamationSweep> sweep) mutable { std::optional<grpc_core::ReclamationSweep> sweep) mutable {
if (sweep.has_value()) { if (sweep.has_value()) {
auto* tp = t.get(); auto* tp = t.get();
tp->active_reclamation = std::move(*sweep); tp->active_reclamation = std::move(*sweep);

View File

@ -23,9 +23,9 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <cstdint> #include <cstdint>
#include <optional>
#include <string> #include <string>
#include "absl/types/optional.h"
#include "src/core/channelz/channelz.h" #include "src/core/channelz/channelz.h"
#include "src/core/ext/transport/chttp2/transport/flow_control.h" #include "src/core/ext/transport/chttp2/transport/flow_control.h"
#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_args.h"
@ -136,20 +136,20 @@ class HttpAnnotation : public CallTracerAnnotationInterface::Annotation {
Type http_type() const { return type_; } Type http_type() const { return type_; }
gpr_timespec time() const { return time_; } gpr_timespec time() const { return time_; }
absl::optional<chttp2::TransportFlowControl::Stats> transport_stats() const { std::optional<chttp2::TransportFlowControl::Stats> transport_stats() const {
return transport_stats_; return transport_stats_;
} }
absl::optional<chttp2::StreamFlowControl::Stats> stream_stats() const { std::optional<chttp2::StreamFlowControl::Stats> stream_stats() const {
return stream_stats_; return stream_stats_;
} }
absl::optional<WriteStats> write_stats() const { return write_stats_; } std::optional<WriteStats> write_stats() const { return write_stats_; }
private: private:
const Type type_; const Type type_;
const gpr_timespec time_; const gpr_timespec time_;
absl::optional<chttp2::TransportFlowControl::Stats> transport_stats_; std::optional<chttp2::TransportFlowControl::Stats> transport_stats_;
absl::optional<chttp2::StreamFlowControl::Stats> stream_stats_; std::optional<chttp2::StreamFlowControl::Stats> stream_stats_;
absl::optional<WriteStats> write_stats_; std::optional<WriteStats> write_stats_;
}; };
} // namespace grpc_core } // namespace grpc_core

View File

@ -330,7 +330,7 @@ std::string TransportFlowControl::Stats::ToString() const {
void StreamFlowControl::SentUpdate(uint32_t announce) { void StreamFlowControl::SentUpdate(uint32_t announce) {
TransportFlowControl::IncomingUpdateContext tfc_upd(tfc_); TransportFlowControl::IncomingUpdateContext tfc_upd(tfc_);
pending_size_ = absl::nullopt; pending_size_ = std::nullopt;
tfc_upd.UpdateAnnouncedWindowDelta(&announced_window_delta_, announce); tfc_upd.UpdateAnnouncedWindowDelta(&announced_window_delta_, announce);
CHECK_EQ(DesiredAnnounceSize(), 0u); CHECK_EQ(DesiredAnnounceSize(), 0u);
std::ignore = tfc_upd.MakeAction(); std::ignore = tfc_upd.MakeAction();

View File

@ -24,6 +24,7 @@
#include <stdint.h> #include <stdint.h>
#include <iosfwd> #include <iosfwd>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
@ -31,7 +32,6 @@
#include "absl/log/check.h" #include "absl/log/check.h"
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/ext/transport/chttp2/transport/http2_settings.h" #include "src/core/ext/transport/chttp2/transport/http2_settings.h"
#include "src/core/lib/debug/trace.h" #include "src/core/lib/debug/trace.h"
#include "src/core/lib/resource_quota/memory_quota.h" #include "src/core/lib/resource_quota/memory_quota.h"
@ -440,7 +440,7 @@ class StreamFlowControl final {
int64_t min_progress_size; int64_t min_progress_size;
int64_t remote_window_delta; int64_t remote_window_delta;
int64_t announced_window_delta; int64_t announced_window_delta;
absl::optional<int64_t> pending_size; std::optional<int64_t> pending_size;
std::string ToString() const; std::string ToString() const;
}; };
@ -459,7 +459,7 @@ class StreamFlowControl final {
int64_t min_progress_size_ = 0; int64_t min_progress_size_ = 0;
int64_t remote_window_delta_ = 0; int64_t remote_window_delta_ = 0;
int64_t announced_window_delta_ = 0; int64_t announced_window_delta_ = 0;
absl::optional<int64_t> pending_size_; std::optional<int64_t> pending_size_;
FlowControlAction UpdateAction(FlowControlAction action); FlowControlAction UpdateAction(FlowControlAction action);
}; };

View File

@ -481,11 +481,11 @@ void Serialize(absl::Span<Http2Frame> frames, SliceBuffer& out) {
// Bytes needed for framing // Bytes needed for framing
buffer_needed += kFrameHeaderSize; buffer_needed += kFrameHeaderSize;
// Bytes needed for frame payload // Bytes needed for frame payload
buffer_needed += absl::visit(SerializeExtraBytesRequired(), frame); buffer_needed += std::visit(SerializeExtraBytesRequired(), frame);
} }
SerializeHeaderAndPayload serialize(buffer_needed, out); SerializeHeaderAndPayload serialize(buffer_needed, out);
for (auto& frame : frames) { for (auto& frame : frames) {
absl::visit(serialize, frame); std::visit(serialize, frame);
} }
} }

View File

@ -19,12 +19,12 @@
#include <cstdint> #include <cstdint>
#include <string> #include <string>
#include <variant>
#include <vector> #include <vector>
#include "absl/status/statusor.h" #include "absl/status/statusor.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/span.h" #include "absl/types/span.h"
#include "absl/types/variant.h"
#include "src/core/lib/slice/slice.h" #include "src/core/lib/slice/slice.h"
#include "src/core/lib/slice/slice_buffer.h" #include "src/core/lib/slice/slice_buffer.h"
@ -171,7 +171,7 @@ struct Http2UnknownFrame {
// A union of all the frame types above, so that we may pass around an // A union of all the frame types above, so that we may pass around an
// arbitrary frame between layers as appropriate. // arbitrary frame between layers as appropriate.
using Http2Frame = using Http2Frame =
absl::variant<Http2DataFrame, Http2HeaderFrame, Http2ContinuationFrame, std::variant<Http2DataFrame, Http2HeaderFrame, Http2ContinuationFrame,
Http2RstStreamFrame, Http2SettingsFrame, Http2PingFrame, Http2RstStreamFrame, Http2SettingsFrame, Http2PingFrame,
Http2GoawayFrame, Http2WindowUpdateFrame, Http2SecurityFrame, Http2GoawayFrame, Http2WindowUpdateFrame, Http2SecurityFrame,
Http2UnknownFrame>; Http2UnknownFrame>;

View File

@ -72,7 +72,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->last_stream_id = (static_cast<uint32_t>(*cur)) << 24; p->last_stream_id = (static_cast<uint32_t>(*cur)) << 24;
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_LSI1: case GRPC_CHTTP2_GOAWAY_LSI1:
if (cur == end) { if (cur == end) {
p->state = GRPC_CHTTP2_GOAWAY_LSI1; p->state = GRPC_CHTTP2_GOAWAY_LSI1;
@ -80,7 +80,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 16; p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 16;
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_LSI2: case GRPC_CHTTP2_GOAWAY_LSI2:
if (cur == end) { if (cur == end) {
p->state = GRPC_CHTTP2_GOAWAY_LSI2; p->state = GRPC_CHTTP2_GOAWAY_LSI2;
@ -88,7 +88,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 8; p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 8;
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_LSI3: case GRPC_CHTTP2_GOAWAY_LSI3:
if (cur == end) { if (cur == end) {
p->state = GRPC_CHTTP2_GOAWAY_LSI3; p->state = GRPC_CHTTP2_GOAWAY_LSI3;
@ -96,7 +96,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->last_stream_id |= (static_cast<uint32_t>(*cur)); p->last_stream_id |= (static_cast<uint32_t>(*cur));
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_ERR0: case GRPC_CHTTP2_GOAWAY_ERR0:
if (cur == end) { if (cur == end) {
p->state = GRPC_CHTTP2_GOAWAY_ERR0; p->state = GRPC_CHTTP2_GOAWAY_ERR0;
@ -104,7 +104,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->error_code = (static_cast<uint32_t>(*cur)) << 24; p->error_code = (static_cast<uint32_t>(*cur)) << 24;
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_ERR1: case GRPC_CHTTP2_GOAWAY_ERR1:
if (cur == end) { if (cur == end) {
p->state = GRPC_CHTTP2_GOAWAY_ERR1; p->state = GRPC_CHTTP2_GOAWAY_ERR1;
@ -112,7 +112,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->error_code |= (static_cast<uint32_t>(*cur)) << 16; p->error_code |= (static_cast<uint32_t>(*cur)) << 16;
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_ERR2: case GRPC_CHTTP2_GOAWAY_ERR2:
if (cur == end) { if (cur == end) {
p->state = GRPC_CHTTP2_GOAWAY_ERR2; p->state = GRPC_CHTTP2_GOAWAY_ERR2;
@ -120,7 +120,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->error_code |= (static_cast<uint32_t>(*cur)) << 8; p->error_code |= (static_cast<uint32_t>(*cur)) << 8;
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_ERR3: case GRPC_CHTTP2_GOAWAY_ERR3:
if (cur == end) { if (cur == end) {
p->state = GRPC_CHTTP2_GOAWAY_ERR3; p->state = GRPC_CHTTP2_GOAWAY_ERR3;
@ -128,7 +128,7 @@ grpc_error_handle grpc_chttp2_goaway_parser_parse(void* parser,
} }
p->error_code |= (static_cast<uint32_t>(*cur)); p->error_code |= (static_cast<uint32_t>(*cur));
++cur; ++cur;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_GOAWAY_DEBUG: case GRPC_CHTTP2_GOAWAY_DEBUG:
if (end != cur) { if (end != cur) {
memcpy(p->debug_data + p->debug_pos, cur, memcpy(p->debug_data + p->debug_pos, cur,

View File

@ -137,7 +137,7 @@ grpc_error_handle grpc_chttp2_settings_parser_parse(void* p,
} }
parser->id = static_cast<uint16_t>((static_cast<uint16_t>(*cur)) << 8); parser->id = static_cast<uint16_t>((static_cast<uint16_t>(*cur)) << 8);
cur++; cur++;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_SPS_ID1: case GRPC_CHTTP2_SPS_ID1:
if (cur == end) { if (cur == end) {
parser->state = GRPC_CHTTP2_SPS_ID1; parser->state = GRPC_CHTTP2_SPS_ID1;
@ -145,7 +145,7 @@ grpc_error_handle grpc_chttp2_settings_parser_parse(void* p,
} }
parser->id = static_cast<uint16_t>(parser->id | (*cur)); parser->id = static_cast<uint16_t>(parser->id | (*cur));
cur++; cur++;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_SPS_VAL0: case GRPC_CHTTP2_SPS_VAL0:
if (cur == end) { if (cur == end) {
parser->state = GRPC_CHTTP2_SPS_VAL0; parser->state = GRPC_CHTTP2_SPS_VAL0;
@ -153,7 +153,7 @@ grpc_error_handle grpc_chttp2_settings_parser_parse(void* p,
} }
parser->value = (static_cast<uint32_t>(*cur)) << 24; parser->value = (static_cast<uint32_t>(*cur)) << 24;
cur++; cur++;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_SPS_VAL1: case GRPC_CHTTP2_SPS_VAL1:
if (cur == end) { if (cur == end) {
parser->state = GRPC_CHTTP2_SPS_VAL1; parser->state = GRPC_CHTTP2_SPS_VAL1;
@ -161,7 +161,7 @@ grpc_error_handle grpc_chttp2_settings_parser_parse(void* p,
} }
parser->value |= (static_cast<uint32_t>(*cur)) << 16; parser->value |= (static_cast<uint32_t>(*cur)) << 16;
cur++; cur++;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_SPS_VAL2: case GRPC_CHTTP2_SPS_VAL2:
if (cur == end) { if (cur == end) {
parser->state = GRPC_CHTTP2_SPS_VAL2; parser->state = GRPC_CHTTP2_SPS_VAL2;
@ -169,7 +169,7 @@ grpc_error_handle grpc_chttp2_settings_parser_parse(void* p,
} }
parser->value |= (static_cast<uint32_t>(*cur)) << 8; parser->value |= (static_cast<uint32_t>(*cur)) << 8;
cur++; cur++;
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_CHTTP2_SPS_VAL3: { case GRPC_CHTTP2_SPS_VAL3: {
if (cur == end) { if (cur == end) {
parser->state = GRPC_CHTTP2_SPS_VAL3; parser->state = GRPC_CHTTP2_SPS_VAL3;

View File

@ -19,6 +19,7 @@
#include <stdint.h> #include <stdint.h>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
@ -26,7 +27,6 @@
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/lib/surface/validate_metadata.h" #include "src/core/lib/surface/validate_metadata.h"
#include "src/core/lib/transport/metadata_batch.h" #include "src/core/lib/transport/metadata_batch.h"
#include "src/core/util/crash.h" #include "src/core/util/crash.h"
@ -337,7 +337,7 @@ class HpackParseResult {
IllegalTableSizeChange illegal_table_size_change; IllegalTableSizeChange illegal_table_size_change;
}; };
std::string key; std::string key;
mutable absl::optional<absl::Status> materialized_status; mutable std::optional<absl::Status> materialized_status;
}; };
RefCountedPtr<HpackParseResultState> state_ = nullptr; RefCountedPtr<HpackParseResultState> state_ = nullptr;

View File

@ -25,8 +25,10 @@
#include <algorithm> #include <algorithm>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
#include <variant>
#include "absl/base/attributes.h" #include "absl/base/attributes.h"
#include "absl/log/check.h" #include "absl/log/check.h"
@ -35,9 +37,7 @@
#include "absl/strings/match.h" #include "absl/strings/match.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h" #include "absl/types/span.h"
#include "absl/types/variant.h"
#include "src/core/ext/transport/chttp2/transport/decode_huff.h" #include "src/core/ext/transport/chttp2/transport/decode_huff.h"
#include "src/core/ext/transport/chttp2/transport/hpack_constants.h" #include "src/core/ext/transport/chttp2/transport/hpack_constants.h"
#include "src/core/ext/transport/chttp2/transport/hpack_parse_result.h" #include "src/core/ext/transport/chttp2/transport/hpack_parse_result.h"
@ -115,7 +115,7 @@ class HPackParser::Input {
// Retrieve the current character, or nullopt if end of stream // Retrieve the current character, or nullopt if end of stream
// Do not advance // Do not advance
absl::optional<uint8_t> peek() const { std::optional<uint8_t> peek() const {
if (end_of_stream()) { if (end_of_stream()) {
return {}; return {};
} }
@ -124,17 +124,17 @@ class HPackParser::Input {
// Retrieve and advance past the current character, or return nullopt if end // Retrieve and advance past the current character, or return nullopt if end
// of stream // of stream
absl::optional<uint8_t> Next() { std::optional<uint8_t> Next() {
if (end_of_stream()) { if (end_of_stream()) {
UnexpectedEOF(/*min_progress_size=*/1); UnexpectedEOF(/*min_progress_size=*/1);
return absl::optional<uint8_t>(); return std::optional<uint8_t>();
} }
return *begin_++; return *begin_++;
} }
// Helper to parse a varint delta on top of value, return nullopt on failure // Helper to parse a varint delta on top of value, return nullopt on failure
// (setting error) // (setting error)
absl::optional<uint32_t> ParseVarint(uint32_t value) { std::optional<uint32_t> ParseVarint(uint32_t value) {
// TODO(ctiller): break out a variant of this when we know there are at // TODO(ctiller): break out a variant of this when we know there are at
// least 5 bytes in input_ // least 5 bytes in input_
auto cur = Next(); auto cur = Next();
@ -190,7 +190,7 @@ class HPackParser::Input {
} }
// Parse a string prefix // Parse a string prefix
absl::optional<StringPrefix> ParseStringPrefix() { std::optional<StringPrefix> ParseStringPrefix() {
auto cur = Next(); auto cur = Next();
if (!cur.has_value()) { if (!cur.has_value()) {
DCHECK(eof_error()); DCHECK(eof_error());
@ -285,17 +285,17 @@ class HPackParser::Input {
private: private:
// Helper to set the error to out of range for ParseVarint // Helper to set the error to out of range for ParseVarint
absl::optional<uint32_t> ParseVarintOutOfRange(uint32_t value, std::optional<uint32_t> ParseVarintOutOfRange(uint32_t value,
uint8_t last_byte) { uint8_t last_byte) {
SetErrorAndStopParsing( SetErrorAndStopParsing(
HpackParseResult::VarintOutOfRangeError(value, last_byte)); HpackParseResult::VarintOutOfRangeError(value, last_byte));
return absl::optional<uint32_t>(); return std::optional<uint32_t>();
} }
// Helper to set the error in the case of a malicious encoding // Helper to set the error in the case of a malicious encoding
absl::optional<uint32_t> ParseVarintMaliciousEncoding() { std::optional<uint32_t> ParseVarintMaliciousEncoding() {
SetErrorAndStopParsing(HpackParseResult::MaliciousVarintEncodingError()); SetErrorAndStopParsing(HpackParseResult::MaliciousVarintEncodingError());
return absl::optional<uint32_t>(); return std::optional<uint32_t>();
} }
// If no error is set, set it to the given error (i.e. first error wins) // If no error is set, set it to the given error (i.e. first error wins)
@ -339,12 +339,12 @@ class HPackParser::Input {
}; };
absl::string_view HPackParser::String::string_view() const { absl::string_view HPackParser::String::string_view() const {
if (auto* p = absl::get_if<Slice>(&value_)) { if (auto* p = std::get_if<Slice>(&value_)) {
return p->as_string_view(); return p->as_string_view();
} else if (auto* p = absl::get_if<absl::Span<const uint8_t>>(&value_)) { } else if (auto* p = std::get_if<absl::Span<const uint8_t>>(&value_)) {
return absl::string_view(reinterpret_cast<const char*>(p->data()), return absl::string_view(reinterpret_cast<const char*>(p->data()),
p->size()); p->size());
} else if (auto* p = absl::get_if<std::vector<uint8_t>>(&value_)) { } else if (auto* p = std::get_if<std::vector<uint8_t>>(&value_)) {
return absl::string_view(reinterpret_cast<const char*>(p->data()), return absl::string_view(reinterpret_cast<const char*>(p->data()),
p->size()); p->size());
} }
@ -396,7 +396,7 @@ HPackParser::String::StringResult HPackParser::String::ParseUncompressed(
} }
} }
absl::optional<std::vector<uint8_t>> HPackParser::String::Unbase64Loop( std::optional<std::vector<uint8_t>> HPackParser::String::Unbase64Loop(
const uint8_t* cur, const uint8_t* end) { const uint8_t* cur, const uint8_t* end) {
while (cur != end && end[-1] == '=') { while (cur != end && end[-1] == '=') {
--end; --end;
@ -478,14 +478,14 @@ absl::optional<std::vector<uint8_t>> HPackParser::String::Unbase64Loop(
} }
HPackParser::String::StringResult HPackParser::String::Unbase64(String s) { HPackParser::String::StringResult HPackParser::String::Unbase64(String s) {
absl::optional<std::vector<uint8_t>> result; std::optional<std::vector<uint8_t>> result;
if (auto* p = absl::get_if<Slice>(&s.value_)) { if (auto* p = std::get_if<Slice>(&s.value_)) {
result = Unbase64Loop(p->begin(), p->end()); result = Unbase64Loop(p->begin(), p->end());
} }
if (auto* p = absl::get_if<absl::Span<const uint8_t>>(&s.value_)) { if (auto* p = std::get_if<absl::Span<const uint8_t>>(&s.value_)) {
result = Unbase64Loop(p->begin(), p->end()); result = Unbase64Loop(p->begin(), p->end());
} }
if (auto* p = absl::get_if<std::vector<uint8_t>>(&s.value_)) { if (auto* p = std::get_if<std::vector<uint8_t>>(&s.value_)) {
result = Unbase64Loop(p->data(), p->data() + p->size()); result = Unbase64Loop(p->data(), p->data() + p->size());
} }
if (!result.has_value()) { if (!result.has_value()) {
@ -648,7 +648,7 @@ class HPackParser::Parser {
// literal key // literal key
return StartParseLiteralKey(true); return StartParseLiteralKey(true);
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case 5: case 5:
case 6: case 6:
// inline encoded key index // inline encoded key index
@ -674,7 +674,7 @@ class HPackParser::Parser {
HpackParseResult::IllegalHpackOpCode()); HpackParseResult::IllegalHpackOpCode());
return false; return false;
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case 9: case 9:
case 10: case 10:
case 11: case 11:
@ -756,7 +756,7 @@ class HPackParser::Parser {
return true; return true;
} }
bool FinishHeaderOmitFromTable(absl::optional<HPackTable::Memento> md) { bool FinishHeaderOmitFromTable(std::optional<HPackTable::Memento> md) {
// Allow higher code to just pass in failures ... simplifies things a bit. // Allow higher code to just pass in failures ... simplifies things a bit.
if (!md.has_value()) return false; if (!md.has_value()) return false;
FinishHeaderOmitFromTable(*md); FinishHeaderOmitFromTable(*md);
@ -960,7 +960,7 @@ class HPackParser::Parser {
: String::Parse(input_, state_.is_string_huff_compressed, : String::Parse(input_, state_.is_string_huff_compressed,
state_.string_length); state_.string_length);
absl::string_view key_string; absl::string_view key_string;
if (auto* s = absl::get_if<Slice>(&state_.key)) { if (auto* s = std::get_if<Slice>(&state_.key)) {
key_string = s->as_string_view(); key_string = s->as_string_view();
if (state_.field_error.ok()) { if (state_.field_error.ok()) {
auto r = ValidateKey(key_string); auto r = ValidateKey(key_string);
@ -970,7 +970,7 @@ class HPackParser::Parser {
} }
} }
} else { } else {
const auto* memento = absl::get<const HPackTable::Memento*>(state_.key); const auto* memento = std::get<const HPackTable::Memento*>(state_.key);
key_string = memento->md.key(); key_string = memento->md.key();
if (state_.field_error.ok() && memento->parse_status.get() != nullptr) { if (state_.field_error.ok() && memento->parse_status.get() != nullptr) {
input_->SetErrorAndContinueParsing(*memento->parse_status); input_->SetErrorAndContinueParsing(*memento->parse_status);
@ -1028,7 +1028,7 @@ class HPackParser::Parser {
} }
// Emit an indexed field // Emit an indexed field
bool FinishIndexed(absl::optional<uint32_t> index) { bool FinishIndexed(std::optional<uint32_t> index) {
state_.dynamic_table_updates_allowed = 0; state_.dynamic_table_updates_allowed = 0;
if (!index.has_value()) return false; if (!index.has_value()) return false;
const auto* elem = state_.hpack_table.Lookup(*index); const auto* elem = state_.hpack_table.Lookup(*index);
@ -1041,7 +1041,7 @@ class HPackParser::Parser {
} }
// finish parsing a max table size change // finish parsing a max table size change
bool FinishMaxTableSize(absl::optional<uint32_t> size) { bool FinishMaxTableSize(std::optional<uint32_t> size) {
if (!size.has_value()) return false; if (!size.has_value()) return false;
if (state_.dynamic_table_updates_allowed == 0) { if (state_.dynamic_table_updates_allowed == 0) {
input_->SetErrorAndStopParsing( input_->SetErrorAndStopParsing(
@ -1072,11 +1072,11 @@ class HPackParser::Parser {
}; };
Slice HPackParser::String::Take() { Slice HPackParser::String::Take() {
if (auto* p = absl::get_if<Slice>(&value_)) { if (auto* p = std::get_if<Slice>(&value_)) {
return p->Copy(); return p->Copy();
} else if (auto* p = absl::get_if<absl::Span<const uint8_t>>(&value_)) { } else if (auto* p = std::get_if<absl::Span<const uint8_t>>(&value_)) {
return Slice::FromCopiedBuffer(*p); return Slice::FromCopiedBuffer(*p);
} else if (auto* p = absl::get_if<std::vector<uint8_t>>(&value_)) { } else if (auto* p = std::get_if<std::vector<uint8_t>>(&value_)) {
return Slice::FromCopiedBuffer(*p); return Slice::FromCopiedBuffer(*p);
} }
GPR_UNREACHABLE_CODE(return Slice()); GPR_UNREACHABLE_CODE(return Slice());
@ -1138,7 +1138,8 @@ grpc_error_handle HPackParser::ParseInput(
HandleMetadataSoftSizeLimitExceeded(&input); HandleMetadataSoftSizeLimitExceeded(&input);
} }
global_stats().IncrementHttp2MetadataSize(state_.frame_length); global_stats().IncrementHttp2MetadataSize(state_.frame_length);
if (call_tracer != nullptr && metadata_buffer_ != nullptr) { if (call_tracer != nullptr && call_tracer->IsSampled() &&
metadata_buffer_ != nullptr) {
MetadataSizesAnnotation metadata_sizes_annotation( MetadataSizesAnnotation metadata_sizes_annotation(
metadata_buffer_, state_.metadata_early_detection.soft_limit(), metadata_buffer_, state_.metadata_early_detection.soft_limit(),
state_.metadata_early_detection.hard_limit()); state_.metadata_early_detection.hard_limit());

View File

@ -24,16 +24,16 @@
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <optional>
#include <string> #include <string>
#include <utility> #include <utility>
#include <variant>
#include <vector> #include <vector>
#include "absl/random/bit_gen_ref.h" #include "absl/random/bit_gen_ref.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h" #include "absl/types/span.h"
#include "absl/types/variant.h"
#include "src/core/ext/transport/chttp2/transport/hpack_parse_result.h" #include "src/core/ext/transport/chttp2/transport/hpack_parse_result.h"
#include "src/core/ext/transport/chttp2/transport/hpack_parser_table.h" #include "src/core/ext/transport/chttp2/transport/hpack_parser_table.h"
#include "src/core/ext/transport/chttp2/transport/legacy_frame.h" #include "src/core/ext/transport/chttp2/transport/legacy_frame.h"
@ -173,11 +173,10 @@ class HPackParser {
static StringResult Unbase64(String s); static StringResult Unbase64(String s);
// Main loop for Unbase64 // Main loop for Unbase64
static absl::optional<std::vector<uint8_t>> Unbase64Loop( static std::optional<std::vector<uint8_t>> Unbase64Loop(const uint8_t* cur,
const uint8_t* cur, const uint8_t* end); const uint8_t* end);
absl::variant<Slice, absl::Span<const uint8_t>, std::vector<uint8_t>> std::variant<Slice, absl::Span<const uint8_t>, std::vector<uint8_t>> value_;
value_;
}; };
// Prefix for a string // Prefix for a string
@ -251,7 +250,7 @@ class HPackParser {
uint8_t dynamic_table_updates_allowed; uint8_t dynamic_table_updates_allowed;
// Current parse state // Current parse state
ParseState parse_state = ParseState::kTop; ParseState parse_state = ParseState::kTop;
absl::variant<const HPackTable::Memento*, Slice> key; std::variant<const HPackTable::Memento*, Slice> key;
}; };
grpc_error_handle ParseInput(Input input, bool is_last, grpc_error_handle ParseInput(Input input, bool is_last,

View File

@ -132,12 +132,12 @@ grpc_http2_error_code Http2Settings::Apply(uint16_t key, uint32_t value) {
return GRPC_HTTP2_NO_ERROR; return GRPC_HTTP2_NO_ERROR;
} }
absl::optional<Http2SettingsFrame> Http2SettingsManager::MaybeSendUpdate() { std::optional<Http2SettingsFrame> Http2SettingsManager::MaybeSendUpdate() {
switch (update_state_) { switch (update_state_) {
case UpdateState::kSending: case UpdateState::kSending:
return absl::nullopt; return std::nullopt;
case UpdateState::kIdle: case UpdateState::kIdle:
if (local_ == sent_) return absl::nullopt; if (local_ == sent_) return std::nullopt;
break; break;
case UpdateState::kFirst: case UpdateState::kFirst:
break; break;

View File

@ -21,10 +21,10 @@
#include <stdint.h> #include <stdint.h>
#include <cstdint> #include <cstdint>
#include <optional>
#include "absl/functional/function_ref.h" #include "absl/functional/function_ref.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "src/core/ext/transport/chttp2/transport/frame.h" #include "src/core/ext/transport/chttp2/transport/frame.h"
#include "src/core/lib/transport/http2_errors.h" #include "src/core/lib/transport/http2_errors.h"
#include "src/core/util/useful.h" #include "src/core/util/useful.h"
@ -152,7 +152,7 @@ class Http2SettingsManager {
Http2Settings& mutable_peer() { return peer_; } Http2Settings& mutable_peer() { return peer_; }
const Http2Settings& peer() const { return peer_; } const Http2Settings& peer() const { return peer_; }
absl::optional<Http2SettingsFrame> MaybeSendUpdate(); std::optional<Http2SettingsFrame> MaybeSendUpdate();
GRPC_MUST_USE_RESULT bool AckLastSend(); GRPC_MUST_USE_RESULT bool AckLastSend();
private: private:

View File

@ -30,14 +30,14 @@
#include <atomic> #include <atomic>
#include <memory> #include <memory>
#include <optional>
#include <utility> #include <utility>
#include <variant>
#include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_map.h"
#include "absl/random/random.h" #include "absl/random/random.h"
#include "absl/status/status.h" #include "absl/status/status.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "src/core/channelz/channelz.h" #include "src/core/channelz/channelz.h"
#include "src/core/ext/transport/chttp2/transport/call_tracer_wrapper.h" #include "src/core/ext/transport/chttp2/transport/call_tracer_wrapper.h"
#include "src/core/ext/transport/chttp2/transport/context_list_entry.h" #include "src/core/ext/transport/chttp2/transport/context_list_entry.h"
@ -475,6 +475,9 @@ struct grpc_chttp2_transport final : public grpc_core::FilterStackTransport,
; ;
/// time duration in between pings /// time duration in between pings
grpc_core::Duration keepalive_time; grpc_core::Duration keepalive_time;
/// Tracks any adjustments to the absolute timestamp of the next keepalive
/// timer callback execution.
grpc_core::Timestamp next_adjusted_keepalive_timestamp;
/// grace period to wait for data after sending a ping before keepalives /// grace period to wait for data after sending a ping before keepalives
/// timeout /// timeout
grpc_core::Duration keepalive_timeout; grpc_core::Duration keepalive_timeout;
@ -606,7 +609,7 @@ struct grpc_chttp2_stream {
grpc_metadata_batch* recv_initial_metadata; grpc_metadata_batch* recv_initial_metadata;
grpc_closure* recv_initial_metadata_ready = nullptr; grpc_closure* recv_initial_metadata_ready = nullptr;
bool* trailing_metadata_available = nullptr; bool* trailing_metadata_available = nullptr;
absl::optional<grpc_core::SliceBuffer>* recv_message = nullptr; std::optional<grpc_core::SliceBuffer>* recv_message = nullptr;
uint32_t* recv_message_flags = nullptr; uint32_t* recv_message_flags = nullptr;
bool* call_failed_before_recv_message = nullptr; bool* call_failed_before_recv_message = nullptr;
grpc_closure* recv_message_ready = nullptr; grpc_closure* recv_message_ready = nullptr;
@ -669,10 +672,10 @@ struct grpc_chttp2_stream {
grpc_core::Chttp2CallTracerWrapper call_tracer_wrapper; grpc_core::Chttp2CallTracerWrapper call_tracer_wrapper;
/// Only set when enabled. // TODO(roth): Remove this when call v3 is supported.
// TODO(roth): Remove this when the call_tracer_in_transport grpc_core::CallTracerInterface* call_tracer = nullptr;
// experiment finishes rolling out. // TODO(yashykt): Remove this once call_tracer_transport_fix is rolled out
grpc_core::CallTracerAnnotationInterface* call_tracer = nullptr; grpc_core::CallTracerAnnotationInterface* parent_call_tracer = nullptr;
/// Only set when enabled. /// Only set when enabled.
std::shared_ptr<grpc_core::TcpTracerInterface> tcp_tracer; std::shared_ptr<grpc_core::TcpTracerInterface> tcp_tracer;
@ -697,6 +700,14 @@ struct grpc_chttp2_stream {
// The last time a stream window update was received. // The last time a stream window update was received.
grpc_core::Timestamp last_window_update_time = grpc_core::Timestamp last_window_update_time =
grpc_core::Timestamp::InfPast(); grpc_core::Timestamp::InfPast();
// TODO(yashykt): Remove this when call v3 is supported.
grpc_core::CallTracerInterface* CallTracer() const {
if (t->is_client) {
return call_tracer;
}
return arena->GetContext<grpc_core::CallTracerInterface>();
}
}; };
#define GRPC_ARG_PING_TIMEOUT_MS "grpc.http2.ping_timeout_ms" #define GRPC_ARG_PING_TIMEOUT_MS "grpc.http2.ping_timeout_ms"
@ -744,7 +755,7 @@ void grpc_chttp2_end_write(grpc_chttp2_transport* t, grpc_error_handle error);
/// - a count of parsed bytes in the event of a partial read: the caller should /// - a count of parsed bytes in the event of a partial read: the caller should
/// offload responsibilities to another thread to continue parsing. /// offload responsibilities to another thread to continue parsing.
/// - or a status in the case of a completed read /// - or a status in the case of a completed read
absl::variant<size_t, absl::Status> grpc_chttp2_perform_read( std::variant<size_t, absl::Status> grpc_chttp2_perform_read(
grpc_chttp2_transport* t, const grpc_slice& slice, grpc_chttp2_transport* t, const grpc_slice& slice,
size_t& requests_started); size_t& requests_started);

View File

@ -29,6 +29,7 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <utility> #include <utility>
#include <variant>
#include "absl/base/attributes.h" #include "absl/base/attributes.h"
#include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_map.h"
@ -39,7 +40,6 @@
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/types/variant.h"
#include "src/core/channelz/channelz.h" #include "src/core/channelz/channelz.h"
#include "src/core/ext/transport/chttp2/transport/call_tracer_wrapper.h" #include "src/core/ext/transport/chttp2/transport/call_tracer_wrapper.h"
#include "src/core/ext/transport/chttp2/transport/flow_control.h" #include "src/core/ext/transport/chttp2/transport/flow_control.h"
@ -206,7 +206,7 @@ std::string FrameTypeString(uint8_t frame_type, uint8_t flags) {
} }
} // namespace } // namespace
absl::variant<size_t, absl::Status> grpc_chttp2_perform_read( std::variant<size_t, absl::Status> grpc_chttp2_perform_read(
grpc_chttp2_transport* t, const grpc_slice& slice, grpc_chttp2_transport* t, const grpc_slice& slice,
size_t& requests_started) { size_t& requests_started) {
GRPC_LATENT_SEE_INNER_SCOPE("grpc_chttp2_perform_read"); GRPC_LATENT_SEE_INNER_SCOPE("grpc_chttp2_perform_read");
@ -268,7 +268,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_0; t->deframe_state = GRPC_DTS_FH_0;
return static_cast<size_t>(cur - beg); return static_cast<size_t>(cur - beg);
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_0: case GRPC_DTS_FH_0:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_frame_size = (static_cast<uint32_t>(*cur)) << 16; t->incoming_frame_size = (static_cast<uint32_t>(*cur)) << 16;
@ -276,7 +276,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_1; t->deframe_state = GRPC_DTS_FH_1;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_1: case GRPC_DTS_FH_1:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_frame_size |= (static_cast<uint32_t>(*cur)) << 8; t->incoming_frame_size |= (static_cast<uint32_t>(*cur)) << 8;
@ -284,7 +284,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_2; t->deframe_state = GRPC_DTS_FH_2;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_2: case GRPC_DTS_FH_2:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_frame_size |= *cur; t->incoming_frame_size |= *cur;
@ -292,7 +292,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_3; t->deframe_state = GRPC_DTS_FH_3;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_3: case GRPC_DTS_FH_3:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_frame_type = *cur; t->incoming_frame_type = *cur;
@ -300,7 +300,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_4; t->deframe_state = GRPC_DTS_FH_4;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_4: case GRPC_DTS_FH_4:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_frame_flags = *cur; t->incoming_frame_flags = *cur;
@ -308,7 +308,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_5; t->deframe_state = GRPC_DTS_FH_5;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_5: case GRPC_DTS_FH_5:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_stream_id = ((static_cast<uint32_t>(*cur)) & 0x7f) << 24; t->incoming_stream_id = ((static_cast<uint32_t>(*cur)) & 0x7f) << 24;
@ -316,7 +316,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_6; t->deframe_state = GRPC_DTS_FH_6;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_6: case GRPC_DTS_FH_6:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 16; t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 16;
@ -324,7 +324,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_7; t->deframe_state = GRPC_DTS_FH_7;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_7: case GRPC_DTS_FH_7:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 8; t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 8;
@ -332,7 +332,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
t->deframe_state = GRPC_DTS_FH_8; t->deframe_state = GRPC_DTS_FH_8;
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FH_8: case GRPC_DTS_FH_8:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
t->incoming_stream_id |= (static_cast<uint32_t>(*cur)); t->incoming_stream_id |= (static_cast<uint32_t>(*cur));
@ -366,7 +366,7 @@ absl::variant<size_t, absl::Status> grpc_chttp2_perform_read(
if (++cur == end) { if (++cur == end) {
return absl::OkStatus(); return absl::OkStatus();
} }
ABSL_FALLTHROUGH_INTENDED; [[fallthrough]];
case GRPC_DTS_FRAME: case GRPC_DTS_FRAME:
DCHECK_LT(cur, end); DCHECK_LT(cur, end);
if (static_cast<uint32_t>(end - cur) == t->incoming_frame_size) { if (static_cast<uint32_t>(end - cur) == t->incoming_frame_size) {
@ -960,8 +960,8 @@ grpc_error_handle grpc_chttp2_header_parser_parse(void* hpack_parser,
s->call_tracer_wrapper.RecordIncomingBytes( s->call_tracer_wrapper.RecordIncomingBytes(
{0, 0, GRPC_SLICE_LENGTH(slice)}); {0, 0, GRPC_SLICE_LENGTH(slice)});
call_tracer = call_tracer =
grpc_core::IsCallTracerInTransportEnabled() grpc_core::IsCallTracerTransportFixEnabled()
? s->arena->GetContext<grpc_core::CallTracerInterface>() ? s->CallTracer()
: s->arena->GetContext<grpc_core::CallTracerAnnotationInterface>(); : s->arena->GetContext<grpc_core::CallTracerAnnotationInterface>();
} }
grpc_error_handle error = parser->Parse( grpc_error_handle error = parser->Parse(

View File

@ -18,9 +18,9 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <algorithm> #include <algorithm>
#include <optional>
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
namespace grpc_core { namespace grpc_core {

View File

@ -89,14 +89,14 @@ void Chttp2PingCallbacks::CancelAll(
ping_requested_ = false; ping_requested_ = false;
} }
absl::optional<uint64_t> Chttp2PingCallbacks::OnPingTimeout( std::optional<uint64_t> Chttp2PingCallbacks::OnPingTimeout(
Duration ping_timeout, Duration ping_timeout,
grpc_event_engine::experimental::EventEngine* event_engine, grpc_event_engine::experimental::EventEngine* event_engine,
Callback callback) { Callback callback) {
CHECK(started_new_ping_without_setting_timeout_); CHECK(started_new_ping_without_setting_timeout_);
started_new_ping_without_setting_timeout_ = false; started_new_ping_without_setting_timeout_ = false;
auto it = inflight_.find(most_recent_inflight_); auto it = inflight_.find(most_recent_inflight_);
if (it == inflight_.end()) return absl::nullopt; if (it == inflight_.end()) return std::nullopt;
it->second.on_timeout = it->second.on_timeout =
event_engine->RunAfter(ping_timeout, std::move(callback)); event_engine->RunAfter(ping_timeout, std::move(callback));
return most_recent_inflight_; return most_recent_inflight_;

View File

@ -21,13 +21,13 @@
#include <stdint.h> #include <stdint.h>
#include <algorithm> #include <algorithm>
#include <optional>
#include <vector> #include <vector>
#include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_map.h"
#include "absl/functional/any_invocable.h" #include "absl/functional/any_invocable.h"
#include "absl/hash/hash.h" #include "absl/hash/hash.h"
#include "absl/random/bit_gen_ref.h" #include "absl/random/bit_gen_ref.h"
#include "absl/types/optional.h"
#include "src/core/lib/debug/trace.h" #include "src/core/lib/debug/trace.h"
#include "src/core/util/time.h" #include "src/core/util/time.h"
@ -85,7 +85,7 @@ class Chttp2PingCallbacks {
// Clears started_new_ping_without_setting_timeout. // Clears started_new_ping_without_setting_timeout.
// Returns the ping id of the ping the timeout was attached to if a timer was // Returns the ping id of the ping the timeout was attached to if a timer was
// started, or nullopt otherwise. // started, or nullopt otherwise.
absl::optional<uint64_t> OnPingTimeout( std::optional<uint64_t> OnPingTimeout(
Duration ping_timeout, Duration ping_timeout,
grpc_event_engine::experimental::EventEngine* event_engine, grpc_event_engine::experimental::EventEngine* event_engine,
Callback callback); Callback callback);

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